1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
|
/*
Copyright (C) 2003-2013 David Bateman
Copyright (C) 2008-2009 Jaroslav Hajek
Copyright (C) 2009-2010 VZLU Prague
This file is part of Octave.
Octave is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
Octave is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with Octave; see the file COPYING. If not, see
<http://www.gnu.org/licenses/>.
Code stolen in large part from Python's, listobject.c, which itself had
no license header. However, thanks to Tim Peters for the parts of the
code I ripped-off.
As required in the Python license the short description of the changes
made are
* convert the sorting code in listobject.cc into a generic class,
replacing PyObject* with the type of the class T.
* replaced usages of malloc, free, memcpy and memmove by standard C++
new [], delete [] and std::copy and std::copy_backward. Note that replacing
memmove by std::copy is possible if the destination starts before the source.
If not, std::copy_backward needs to be used.
* templatize comparison operator in most methods, provide possible dispatch
* duplicate methods to avoid by-the-way indexed sorting
* add methods for verifying sortedness of array
* row sorting via breadth-first tree subsorting
* binary lookup and sequential binary lookup optimized for dense downsampling.
* NOTE: the memory management routines rely on the fact that delete [] silently
ignores null pointers. Don't gripe about the missing checks - they're there.
The Python license is
PSF LICENSE AGREEMENT FOR PYTHON 2.3
--------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using Python 2.3 software in source or binary form and its
associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 2.3
alone or in any derivative version, provided, however, that PSF's
License Agreement and PSF's notice of copyright, i.e., "Copyright (c)
2001, 2002, 2003 Python Software Foundation; All Rights Reserved" are
retained in Python 2.3 alone or in any derivative version prepared by
Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 2.3 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 2.3.
4. PSF is making Python 2.3 available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.3 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.3,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python 2.3, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cassert>
#include <algorithm>
#include <functional>
#include <cstring>
#include <stack>
#include "lo-mappers.h"
#include "quit.h"
#include "oct-sort.h"
#include "oct-locbuf.h"
template <class T>
octave_sort<T>::octave_sort (void) :
compare (ascending_compare), ms (0)
{
}
template <class T>
octave_sort<T>::octave_sort (compare_fcn_type comp)
: compare (comp), ms (0)
{
}
template <class T>
octave_sort<T>::~octave_sort ()
{
delete ms;
}
template <class T>
void
octave_sort<T>::set_compare (sortmode mode)
{
if (mode == ASCENDING)
compare = ascending_compare;
else if (mode == DESCENDING)
compare = descending_compare;
else
compare = 0;
}
template <class T>
template <class Comp>
void
octave_sort<T>::binarysort (T *data, octave_idx_type nel,
octave_idx_type start, Comp comp)
{
if (start == 0)
++start;
for (; start < nel; ++start)
{
/* set l to where *start belongs */
octave_idx_type l = 0, r = start;
T pivot = data[start];
/* Invariants:
* pivot >= all in [lo, l).
* pivot < all in [r, start).
* The second is vacuously true at the start.
*/
do
{
octave_idx_type p = l + ((r - l) >> 1);
if (comp (pivot, data[p]))
r = p;
else
l = p+1;
}
while (l < r);
/* The invariants still hold, so pivot >= all in [lo, l) and
pivot < all in [l, start), so pivot belongs at l. Note
that if there are elements equal to pivot, l points to the
first slot after them -- that's why this sort is stable.
Slide over to make room.
Caution: using memmove is much slower under MSVC 5;
we're not usually moving many slots. */
// NOTE: using swap and going upwards appears to be faster.
for (octave_idx_type p = l; p < start; p++)
std::swap (pivot, data[p]);
data[start] = pivot;
}
return;
}
template <class T>
template <class Comp>
void
octave_sort<T>::binarysort (T *data, octave_idx_type *idx, octave_idx_type nel,
octave_idx_type start, Comp comp)
{
if (start == 0)
++start;
for (; start < nel; ++start)
{
/* set l to where *start belongs */
octave_idx_type l = 0, r = start;
T pivot = data[start];
/* Invariants:
* pivot >= all in [lo, l).
* pivot < all in [r, start).
* The second is vacuously true at the start.
*/
do
{
octave_idx_type p = l + ((r - l) >> 1);
if (comp (pivot, data[p]))
r = p;
else
l = p+1;
}
while (l < r);
/* The invariants still hold, so pivot >= all in [lo, l) and
pivot < all in [l, start), so pivot belongs at l. Note
that if there are elements equal to pivot, l points to the
first slot after them -- that's why this sort is stable.
Slide over to make room.
Caution: using memmove is much slower under MSVC 5;
we're not usually moving many slots. */
// NOTE: using swap and going upwards appears to be faster.
for (octave_idx_type p = l; p < start; p++)
std::swap (pivot, data[p]);
data[start] = pivot;
octave_idx_type ipivot = idx[start];
for (octave_idx_type p = l; p < start; p++)
std::swap (ipivot, idx[p]);
idx[start] = ipivot;
}
return;
}
/*
Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
is required on entry. "A run" is the longest ascending sequence, with
lo[0] <= lo[1] <= lo[2] <= ...
or the longest descending sequence, with
lo[0] > lo[1] > lo[2] > ...
DESCENDING is set to false in the former case, or to true in the latter.
For its intended use in a stable mergesort, the strictness of the defn of
"descending" is needed so that the caller can safely reverse a descending
sequence without violating stability (strict > ensures there are no equal
elements to get out of order).
Returns -1 in case of error.
*/
template <class T>
template <class Comp>
octave_idx_type
octave_sort<T>::count_run (T *lo, octave_idx_type nel, bool& descending,
Comp comp)
{
octave_idx_type n;
T *hi = lo + nel;
descending = false;
++lo;
if (lo == hi)
return 1;
n = 2;
if (comp (*lo, *(lo-1)))
{
descending = true;
for (lo = lo+1; lo < hi; ++lo, ++n)
{
if (comp (*lo, *(lo-1)))
;
else
break;
}
}
else
{
for (lo = lo+1; lo < hi; ++lo, ++n)
{
if (comp (*lo, *(lo-1)))
break;
}
}
return n;
}
/*
Locate the proper position of key in a sorted vector; if the vector contains
an element equal to key, return the position immediately to the left of
the leftmost equal element. [gallop_right() does the same except returns
the position to the right of the rightmost equal element (if any).]
"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
"hint" is an index at which to begin the search, 0 <= hint < n. The closer
hint is to the final result, the faster this runs.
The return value is the int k in 0..n such that
a[k-1] < key <= a[k]
pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
key belongs at index k; or, IOW, the first k elements of a should precede
key, and the last n-k should follow key.
Returns -1 on error. See listsort.txt for info on the method.
*/
template <class T>
template <class Comp>
octave_idx_type
octave_sort<T>::gallop_left (T key, T *a, octave_idx_type n,
octave_idx_type hint,
Comp comp)
{
octave_idx_type ofs;
octave_idx_type lastofs;
octave_idx_type k;
a += hint;
lastofs = 0;
ofs = 1;
if (comp (*a, key))
{
/* a[hint] < key -- gallop right, until
* a[hint + lastofs] < key <= a[hint + ofs]
*/
const octave_idx_type maxofs = n - hint; /* &a[n-1] is highest */
while (ofs < maxofs)
{
if (comp (a[ofs], key))
{
lastofs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) /* int overflow */
ofs = maxofs;
}
else /* key <= a[hint + ofs] */
break;
}
if (ofs > maxofs)
ofs = maxofs;
/* Translate back to offsets relative to &a[0]. */
lastofs += hint;
ofs += hint;
}
else
{
/* key <= a[hint] -- gallop left, until
* a[hint - ofs] < key <= a[hint - lastofs]
*/
const octave_idx_type maxofs = hint + 1; /* &a[0] is lowest */
while (ofs < maxofs)
{
if (comp (*(a-ofs), key))
break;
/* key <= a[hint - ofs] */
lastofs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) /* int overflow */
ofs = maxofs;
}
if (ofs > maxofs)
ofs = maxofs;
/* Translate back to positive offsets relative to &a[0]. */
k = lastofs;
lastofs = hint - ofs;
ofs = hint - k;
}
a -= hint;
/* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
* right of lastofs but no farther right than ofs. Do a binary
* search, with invariant a[lastofs-1] < key <= a[ofs].
*/
++lastofs;
while (lastofs < ofs)
{
octave_idx_type m = lastofs + ((ofs - lastofs) >> 1);
if (comp (a[m], key))
lastofs = m+1; /* a[m] < key */
else
ofs = m; /* key <= a[m] */
}
return ofs;
}
/*
Exactly like gallop_left(), except that if key already exists in a[0:n],
finds the position immediately to the right of the rightmost equal value.
The return value is the int k in 0..n such that
a[k-1] <= key < a[k]
or -1 if error.
The code duplication is massive, but this is enough different given that
we're sticking to "<" comparisons that it's much harder to follow if
written as one routine with yet another "left or right?" flag.
*/
template <class T>
template <class Comp>
octave_idx_type
octave_sort<T>::gallop_right (T key, T *a, octave_idx_type n,
octave_idx_type hint,
Comp comp)
{
octave_idx_type ofs;
octave_idx_type lastofs;
octave_idx_type k;
a += hint;
lastofs = 0;
ofs = 1;
if (comp (key, *a))
{
/* key < a[hint] -- gallop left, until
* a[hint - ofs] <= key < a[hint - lastofs]
*/
const octave_idx_type maxofs = hint + 1; /* &a[0] is lowest */
while (ofs < maxofs)
{
if (comp (key, *(a-ofs)))
{
lastofs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) /* int overflow */
ofs = maxofs;
}
else /* a[hint - ofs] <= key */
break;
}
if (ofs > maxofs)
ofs = maxofs;
/* Translate back to positive offsets relative to &a[0]. */
k = lastofs;
lastofs = hint - ofs;
ofs = hint - k;
}
else
{
/* a[hint] <= key -- gallop right, until
* a[hint + lastofs] <= key < a[hint + ofs]
*/
const octave_idx_type maxofs = n - hint; /* &a[n-1] is highest */
while (ofs < maxofs)
{
if (comp (key, a[ofs]))
break;
/* a[hint + ofs] <= key */
lastofs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) /* int overflow */
ofs = maxofs;
}
if (ofs > maxofs)
ofs = maxofs;
/* Translate back to offsets relative to &a[0]. */
lastofs += hint;
ofs += hint;
}
a -= hint;
/* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
* right of lastofs but no farther right than ofs. Do a binary
* search, with invariant a[lastofs-1] <= key < a[ofs].
*/
++lastofs;
while (lastofs < ofs)
{
octave_idx_type m = lastofs + ((ofs - lastofs) >> 1);
if (comp (key, a[m]))
ofs = m; /* key < a[m] */
else
lastofs = m+1; /* a[m] <= key */
}
return ofs;
}
static inline octave_idx_type
roundupsize (octave_idx_type n)
{
unsigned int nbits = 3;
octave_idx_type n2 = static_cast<octave_idx_type> (n) >> 8;
/* Round up:
* If n < 256, to a multiple of 8.
* If n < 2048, to a multiple of 64.
* If n < 16384, to a multiple of 512.
* If n < 131072, to a multiple of 4096.
* If n < 1048576, to a multiple of 32768.
* If n < 8388608, to a multiple of 262144.
* If n < 67108864, to a multiple of 2097152.
* If n < 536870912, to a multiple of 16777216.
* ...
* If n < 2**(5+3*i), to a multiple of 2**(3*i).
*
* This over-allocates proportional to the list size, making room
* for additional growth. The over-allocation is mild, but is
* enough to give linear-time amortized behavior over a long
* sequence of appends() in the presence of a poorly-performing
* system realloc() (which is a reality, e.g., across all flavors
* of Windows, with Win9x behavior being particularly bad -- and
* we've still got address space fragmentation problems on Win9x
* even with this scheme, although it requires much longer lists to
* provoke them than it used to).
*/
while (n2)
{
n2 >>= 3;
nbits += 3;
}
return ((n >> nbits) + 1) << nbits;
}
/* Ensure enough temp memory for 'need' array slots is available.
* Returns 0 on success and -1 if the memory can't be gotten.
*/
template <class T>
void
octave_sort<T>::MergeState::getmem (octave_idx_type need)
{
if (need <= alloced)
return;
need = roundupsize (need);
/* Don't realloc! That can cost cycles to copy the old data, but
* we don't care what's in the block.
*/
delete [] a;
delete [] ia; // Must do this or fool possible next getmemi.
a = new T [need];
alloced = need;
}
template <class T>
void
octave_sort<T>::MergeState::getmemi (octave_idx_type need)
{
if (ia && need <= alloced)
return;
need = roundupsize (need);
/* Don't realloc! That can cost cycles to copy the old data, but
* we don't care what's in the block.
*/
delete [] a;
delete [] ia;
a = new T [need];
ia = new octave_idx_type [need];
alloced = need;
}
/* Merge the na elements starting at pa with the nb elements starting at pb
* in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
* Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
* merge, and should have na <= nb. See listsort.txt for more info.
* Return 0 if successful, -1 if error.
*/
template <class T>
template <class Comp>
int
octave_sort<T>::merge_lo (T *pa, octave_idx_type na,
T *pb, octave_idx_type nb,
Comp comp)
{
octave_idx_type k;
T *dest;
int result = -1; /* guilty until proved innocent */
octave_idx_type min_gallop = ms->min_gallop;
ms->getmem (na);
std::copy (pa, pa + na, ms->a);
dest = pa;
pa = ms->a;
*dest++ = *pb++;
--nb;
if (nb == 0)
goto Succeed;
if (na == 1)
goto CopyB;
for (;;)
{
octave_idx_type acount = 0; /* # of times A won in a row */
octave_idx_type bcount = 0; /* # of times B won in a row */
/* Do the straightforward thing until (if ever) one run
* appears to win consistently.
*/
for (;;)
{
// FIXME: these loops are candidates for further optimizations.
// Rather than testing everything in each cycle, it may be more
// efficient to do it in hunks.
if (comp (*pb, *pa))
{
*dest++ = *pb++;
++bcount;
acount = 0;
--nb;
if (nb == 0)
goto Succeed;
if (bcount >= min_gallop)
break;
}
else
{
*dest++ = *pa++;
++acount;
bcount = 0;
--na;
if (na == 1)
goto CopyB;
if (acount >= min_gallop)
break;
}
}
/* One run is winning so consistently that galloping may
* be a huge win. So try that, and continue galloping until
* (if ever) neither run appears to be winning consistently
* anymore.
*/
++min_gallop;
do
{
min_gallop -= min_gallop > 1;
ms->min_gallop = min_gallop;
k = gallop_right (*pb, pa, na, 0, comp);
acount = k;
if (k)
{
if (k < 0)
goto Fail;
dest = std::copy (pa, pa + k, dest);
pa += k;
na -= k;
if (na == 1)
goto CopyB;
/* na==0 is impossible now if the comparison
* function is consistent, but we can't assume
* that it is.
*/
if (na == 0)
goto Succeed;
}
*dest++ = *pb++;
--nb;
if (nb == 0)
goto Succeed;
k = gallop_left (*pa, pb, nb, 0, comp);
bcount = k;
if (k)
{
if (k < 0)
goto Fail;
dest = std::copy (pb, pb + k, dest);
pb += k;
nb -= k;
if (nb == 0)
goto Succeed;
}
*dest++ = *pa++;
--na;
if (na == 1)
goto CopyB;
}
while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
++min_gallop; /* penalize it for leaving galloping mode */
ms->min_gallop = min_gallop;
}
Succeed:
result = 0;
Fail:
if (na)
std::copy (pa, pa + na, dest);
return result;
CopyB:
/* The last element of pa belongs at the end of the merge. */
std::copy (pb, pb + nb, dest);
dest[nb] = *pa;
return 0;
}
template <class T>
template <class Comp>
int
octave_sort<T>::merge_lo (T *pa, octave_idx_type *ipa, octave_idx_type na,
T *pb, octave_idx_type *ipb, octave_idx_type nb,
Comp comp)
{
octave_idx_type k;
T *dest;
octave_idx_type *idest;
int result = -1; /* guilty until proved innocent */
octave_idx_type min_gallop = ms->min_gallop;
ms->getmemi (na);
std::copy (pa, pa + na, ms->a);
std::copy (ipa, ipa + na, ms->ia);
dest = pa; idest = ipa;
pa = ms->a; ipa = ms->ia;
*dest++ = *pb++; *idest++ = *ipb++;
--nb;
if (nb == 0)
goto Succeed;
if (na == 1)
goto CopyB;
for (;;)
{
octave_idx_type acount = 0; /* # of times A won in a row */
octave_idx_type bcount = 0; /* # of times B won in a row */
/* Do the straightforward thing until (if ever) one run
* appears to win consistently.
*/
for (;;)
{
if (comp (*pb, *pa))
{
*dest++ = *pb++; *idest++ = *ipb++;
++bcount;
acount = 0;
--nb;
if (nb == 0)
goto Succeed;
if (bcount >= min_gallop)
break;
}
else
{
*dest++ = *pa++; *idest++ = *ipa++;
++acount;
bcount = 0;
--na;
if (na == 1)
goto CopyB;
if (acount >= min_gallop)
break;
}
}
/* One run is winning so consistently that galloping may
* be a huge win. So try that, and continue galloping until
* (if ever) neither run appears to be winning consistently
* anymore.
*/
++min_gallop;
do
{
min_gallop -= min_gallop > 1;
ms->min_gallop = min_gallop;
k = gallop_right (*pb, pa, na, 0, comp);
acount = k;
if (k)
{
if (k < 0)
goto Fail;
dest = std::copy (pa, pa + k, dest);
idest = std::copy (ipa, ipa + k, idest);
pa += k; ipa += k;
na -= k;
if (na == 1)
goto CopyB;
/* na==0 is impossible now if the comparison
* function is consistent, but we can't assume
* that it is.
*/
if (na == 0)
goto Succeed;
}
*dest++ = *pb++; *idest++ = *ipb++;
--nb;
if (nb == 0)
goto Succeed;
k = gallop_left (*pa, pb, nb, 0, comp);
bcount = k;
if (k)
{
if (k < 0)
goto Fail;
dest = std::copy (pb, pb + k, dest);
idest = std::copy (ipb, ipb + k, idest);
pb += k; ipb += k;
nb -= k;
if (nb == 0)
goto Succeed;
}
*dest++ = *pa++; *idest++ = *ipa++;
--na;
if (na == 1)
goto CopyB;
}
while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
++min_gallop; /* penalize it for leaving galloping mode */
ms->min_gallop = min_gallop;
}
Succeed:
result = 0;
Fail:
if (na)
{
std::copy (pa, pa + na, dest);
std::copy (ipa, ipa + na, idest);
}
return result;
CopyB:
/* The last element of pa belongs at the end of the merge. */
std::copy (pb, pb + nb, dest);
std::copy (ipb, ipb + nb, idest);
dest[nb] = *pa;
idest[nb] = *ipa;
return 0;
}
/* Merge the na elements starting at pa with the nb elements starting at pb
* in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
* Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
* merge, and should have na >= nb. See listsort.txt for more info.
* Return 0 if successful, -1 if error.
*/
template <class T>
template <class Comp>
int
octave_sort<T>::merge_hi (T *pa, octave_idx_type na,
T *pb, octave_idx_type nb,
Comp comp)
{
octave_idx_type k;
T *dest;
int result = -1; /* guilty until proved innocent */
T *basea, *baseb;
octave_idx_type min_gallop = ms->min_gallop;
ms->getmem (nb);
dest = pb + nb - 1;
std::copy (pb, pb + nb, ms->a);
basea = pa;
baseb = ms->a;
pb = ms->a + nb - 1;
pa += na - 1;
*dest-- = *pa--;
--na;
if (na == 0)
goto Succeed;
if (nb == 1)
goto CopyA;
for (;;)
{
octave_idx_type acount = 0; /* # of times A won in a row */
octave_idx_type bcount = 0; /* # of times B won in a row */
/* Do the straightforward thing until (if ever) one run
* appears to win consistently.
*/
for (;;)
{
if (comp (*pb, *pa))
{
*dest-- = *pa--;
++acount;
bcount = 0;
--na;
if (na == 0)
goto Succeed;
if (acount >= min_gallop)
break;
}
else
{
*dest-- = *pb--;
++bcount;
acount = 0;
--nb;
if (nb == 1)
goto CopyA;
if (bcount >= min_gallop)
break;
}
}
/* One run is winning so consistently that galloping may
* be a huge win. So try that, and continue galloping until
* (if ever) neither run appears to be winning consistently
* anymore.
*/
++min_gallop;
do
{
min_gallop -= min_gallop > 1;
ms->min_gallop = min_gallop;
k = gallop_right (*pb, basea, na, na-1, comp);
if (k < 0)
goto Fail;
k = na - k;
acount = k;
if (k)
{
dest = std::copy_backward (pa+1 - k, pa+1, dest+1) - 1;
pa -= k;
na -= k;
if (na == 0)
goto Succeed;
}
*dest-- = *pb--;
--nb;
if (nb == 1)
goto CopyA;
k = gallop_left (*pa, baseb, nb, nb-1, comp);
if (k < 0)
goto Fail;
k = nb - k;
bcount = k;
if (k)
{
dest -= k;
pb -= k;
std::copy (pb+1, pb+1 + k, dest+1);
nb -= k;
if (nb == 1)
goto CopyA;
/* nb==0 is impossible now if the comparison
* function is consistent, but we can't assume
* that it is.
*/
if (nb == 0)
goto Succeed;
}
*dest-- = *pa--;
--na;
if (na == 0)
goto Succeed;
} while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
++min_gallop; /* penalize it for leaving galloping mode */
ms->min_gallop = min_gallop;
}
Succeed:
result = 0;
Fail:
if (nb)
std::copy (baseb, baseb + nb, dest-(nb-1));
return result;
CopyA:
/* The first element of pb belongs at the front of the merge. */
dest = std::copy_backward (pa+1 - na, pa+1, dest+1) - 1;
pa -= na;
*dest = *pb;
return 0;
}
template <class T>
template <class Comp>
int
octave_sort<T>::merge_hi (T *pa, octave_idx_type *ipa, octave_idx_type na,
T *pb, octave_idx_type *ipb, octave_idx_type nb,
Comp comp)
{
octave_idx_type k;
T *dest;
octave_idx_type *idest;
int result = -1; /* guilty until proved innocent */
T *basea, *baseb;
octave_idx_type *ibaseb;
octave_idx_type min_gallop = ms->min_gallop;
ms->getmemi (nb);
dest = pb + nb - 1;
idest = ipb + nb - 1;
std::copy (pb, pb + nb, ms->a);
std::copy (ipb, ipb + nb, ms->ia);
basea = pa;
baseb = ms->a; ibaseb = ms->ia;
pb = ms->a + nb - 1; ipb = ms->ia + nb - 1;
pa += na - 1; ipa += na - 1;
*dest-- = *pa--; *idest-- = *ipa--;
--na;
if (na == 0)
goto Succeed;
if (nb == 1)
goto CopyA;
for (;;)
{
octave_idx_type acount = 0; /* # of times A won in a row */
octave_idx_type bcount = 0; /* # of times B won in a row */
/* Do the straightforward thing until (if ever) one run
* appears to win consistently.
*/
for (;;)
{
if (comp (*pb, *pa))
{
*dest-- = *pa--; *idest-- = *ipa--;
++acount;
bcount = 0;
--na;
if (na == 0)
goto Succeed;
if (acount >= min_gallop)
break;
}
else
{
*dest-- = *pb--; *idest-- = *ipb--;
++bcount;
acount = 0;
--nb;
if (nb == 1)
goto CopyA;
if (bcount >= min_gallop)
break;
}
}
/* One run is winning so consistently that galloping may
* be a huge win. So try that, and continue galloping until
* (if ever) neither run appears to be winning consistently
* anymore.
*/
++min_gallop;
do
{
min_gallop -= min_gallop > 1;
ms->min_gallop = min_gallop;
k = gallop_right (*pb, basea, na, na-1, comp);
if (k < 0)
goto Fail;
k = na - k;
acount = k;
if (k)
{
dest = std::copy_backward (pa+1 - k, pa+1, dest+1) - 1;
idest = std::copy_backward (ipa+1 - k, ipa+1, idest+1) - 1;
pa -= k; ipa -= k;
na -= k;
if (na == 0)
goto Succeed;
}
*dest-- = *pb--; *idest-- = *ipb--;
--nb;
if (nb == 1)
goto CopyA;
k = gallop_left (*pa, baseb, nb, nb-1, comp);
if (k < 0)
goto Fail;
k = nb - k;
bcount = k;
if (k)
{
dest -= k; idest -= k;
pb -= k; ipb -= k;
std::copy (pb+1, pb+1 + k, dest+1);
std::copy (ipb+1, ipb+1 + k, idest+1);
nb -= k;
if (nb == 1)
goto CopyA;
/* nb==0 is impossible now if the comparison
* function is consistent, but we can't assume
* that it is.
*/
if (nb == 0)
goto Succeed;
}
*dest-- = *pa--; *idest-- = *ipa--;
--na;
if (na == 0)
goto Succeed;
} while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
++min_gallop; /* penalize it for leaving galloping mode */
ms->min_gallop = min_gallop;
}
Succeed:
result = 0;
Fail:
if (nb)
{
std::copy (baseb, baseb + nb, dest-(nb-1));
std::copy (ibaseb, ibaseb + nb, idest-(nb-1));
}
return result;
CopyA:
/* The first element of pb belongs at the front of the merge. */
dest = std::copy_backward (pa+1 - na, pa+1, dest+1) - 1;
idest = std::copy_backward (ipa+1 - na, ipa+1, idest+1) - 1;
pa -= na; ipa -= na;
*dest = *pb; *idest = *ipb;
return 0;
}
/* Merge the two runs at stack indices i and i+1.
* Returns 0 on success, -1 on error.
*/
template <class T>
template <class Comp>
int
octave_sort<T>::merge_at (octave_idx_type i, T *data,
Comp comp)
{
T *pa, *pb;
octave_idx_type na, nb;
octave_idx_type k;
pa = data + ms->pending[i].base;
na = ms->pending[i].len;
pb = data + ms->pending[i+1].base;
nb = ms->pending[i+1].len;
/* Record the length of the combined runs; if i is the 3rd-last
* run now, also slide over the last run (which isn't involved
* in this merge). The current run i+1 goes away in any case.
*/
ms->pending[i].len = na + nb;
if (i == ms->n - 3)
ms->pending[i+1] = ms->pending[i+2];
ms->n--;
/* Where does b start in a? Elements in a before that can be
* ignored (already in place).
*/
k = gallop_right (*pb, pa, na, 0, comp);
if (k < 0)
return -1;
pa += k;
na -= k;
if (na == 0)
return 0;
/* Where does a end in b? Elements in b after that can be
* ignored (already in place).
*/
nb = gallop_left (pa[na-1], pb, nb, nb-1, comp);
if (nb <= 0)
return nb;
/* Merge what remains of the runs, using a temp array with
* min (na, nb) elements.
*/
if (na <= nb)
return merge_lo (pa, na, pb, nb, comp);
else
return merge_hi (pa, na, pb, nb, comp);
}
template <class T>
template <class Comp>
int
octave_sort<T>::merge_at (octave_idx_type i, T *data, octave_idx_type *idx,
Comp comp)
{
T *pa, *pb;
octave_idx_type *ipa, *ipb;
octave_idx_type na, nb;
octave_idx_type k;
pa = data + ms->pending[i].base;
ipa = idx + ms->pending[i].base;
na = ms->pending[i].len;
pb = data + ms->pending[i+1].base;
ipb = idx + ms->pending[i+1].base;
nb = ms->pending[i+1].len;
/* Record the length of the combined runs; if i is the 3rd-last
* run now, also slide over the last run (which isn't involved
* in this merge). The current run i+1 goes away in any case.
*/
ms->pending[i].len = na + nb;
if (i == ms->n - 3)
ms->pending[i+1] = ms->pending[i+2];
ms->n--;
/* Where does b start in a? Elements in a before that can be
* ignored (already in place).
*/
k = gallop_right (*pb, pa, na, 0, comp);
if (k < 0)
return -1;
pa += k; ipa += k;
na -= k;
if (na == 0)
return 0;
/* Where does a end in b? Elements in b after that can be
* ignored (already in place).
*/
nb = gallop_left (pa[na-1], pb, nb, nb-1, comp);
if (nb <= 0)
return nb;
/* Merge what remains of the runs, using a temp array with
* min (na, nb) elements.
*/
if (na <= nb)
return merge_lo (pa, ipa, na, pb, ipb, nb, comp);
else
return merge_hi (pa, ipa, na, pb, ipb, nb, comp);
}
/* Examine the stack of runs waiting to be merged, merging adjacent runs
* until the stack invariants are re-established:
*
* 1. len[-3] > len[-2] + len[-1]
* 2. len[-2] > len[-1]
*
* See listsort.txt for more info.
*
* Returns 0 on success, -1 on error.
*/
template <class T>
template <class Comp>
int
octave_sort<T>::merge_collapse (T *data, Comp comp)
{
struct s_slice *p = ms->pending;
while (ms->n > 1)
{
octave_idx_type n = ms->n - 2;
if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len)
{
if (p[n-1].len < p[n+1].len)
--n;
if (merge_at (n, data, comp) < 0)
return -1;
}
else if (p[n].len <= p[n+1].len)
{
if (merge_at (n, data, comp) < 0)
return -1;
}
else
break;
}
return 0;
}
template <class T>
template <class Comp>
int
octave_sort<T>::merge_collapse (T *data, octave_idx_type *idx, Comp comp)
{
struct s_slice *p = ms->pending;
while (ms->n > 1)
{
octave_idx_type n = ms->n - 2;
if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len)
{
if (p[n-1].len < p[n+1].len)
--n;
if (merge_at (n, data, idx, comp) < 0)
return -1;
}
else if (p[n].len <= p[n+1].len)
{
if (merge_at (n, data, idx, comp) < 0)
return -1;
}
else
break;
}
return 0;
}
/* Regardless of invariants, merge all runs on the stack until only one
* remains. This is used at the end of the mergesort.
*
* Returns 0 on success, -1 on error.
*/
template <class T>
template <class Comp>
int
octave_sort<T>::merge_force_collapse (T *data, Comp comp)
{
struct s_slice *p = ms->pending;
while (ms->n > 1)
{
octave_idx_type n = ms->n - 2;
if (n > 0 && p[n-1].len < p[n+1].len)
--n;
if (merge_at (n, data, comp) < 0)
return -1;
}
return 0;
}
template <class T>
template <class Comp>
int
octave_sort<T>::merge_force_collapse (T *data, octave_idx_type *idx, Comp comp)
{
struct s_slice *p = ms->pending;
while (ms->n > 1)
{
octave_idx_type n = ms->n - 2;
if (n > 0 && p[n-1].len < p[n+1].len)
--n;
if (merge_at (n, data, idx, comp) < 0)
return -1;
}
return 0;
}
/* Compute a good value for the minimum run length; natural runs shorter
* than this are boosted artificially via binary insertion.
*
* If n < 64, return n (it's too small to bother with fancy stuff).
* Else if n is an exact power of 2, return 32.
* Else return an int k, 32 <= k <= 64, such that n/k is close to, but
* strictly less than, an exact power of 2.
*
* See listsort.txt for more info.
*/
template <class T>
octave_idx_type
octave_sort<T>::merge_compute_minrun (octave_idx_type n)
{
octave_idx_type r = 0; /* becomes 1 if any 1 bits are shifted off */
while (n >= 64)
{
r |= n & 1;
n >>= 1;
}
return n + r;
}
template <class T>
template <class Comp>
void
octave_sort<T>::sort (T *data, octave_idx_type nel, Comp comp)
{
/* Re-initialize the Mergestate as this might be the second time called */
if (! ms) ms = new MergeState;
ms->reset ();
ms->getmem (1024);
if (nel > 1)
{
octave_idx_type nremaining = nel;
octave_idx_type lo = 0;
/* March over the array once, left to right, finding natural runs,
* and extending short natural runs to minrun elements.
*/
octave_idx_type minrun = merge_compute_minrun (nremaining);
do
{
bool descending;
octave_idx_type n;
/* Identify next run. */
n = count_run (data + lo, nremaining, descending, comp);
if (n < 0)
goto fail;
if (descending)
std::reverse (data + lo, data + lo + n);
/* If short, extend to min (minrun, nremaining). */
if (n < minrun)
{
const octave_idx_type force = nremaining <= minrun ? nremaining
: minrun;
binarysort (data + lo, force, n, comp);
n = force;
}
/* Push run onto pending-runs stack, and maybe merge. */
assert (ms->n < MAX_MERGE_PENDING);
ms->pending[ms->n].base = lo;
ms->pending[ms->n].len = n;
ms->n++;
if (merge_collapse (data, comp) < 0)
goto fail;
/* Advance to find next run. */
lo += n;
nremaining -= n;
}
while (nremaining);
merge_force_collapse (data, comp);
}
fail:
return;
}
template <class T>
template <class Comp>
void
octave_sort<T>::sort (T *data, octave_idx_type *idx, octave_idx_type nel,
Comp comp)
{
/* Re-initialize the Mergestate as this might be the second time called */
if (! ms) ms = new MergeState;
ms->reset ();
ms->getmemi (1024);
if (nel > 1)
{
octave_idx_type nremaining = nel;
octave_idx_type lo = 0;
/* March over the array once, left to right, finding natural runs,
* and extending short natural runs to minrun elements.
*/
octave_idx_type minrun = merge_compute_minrun (nremaining);
do
{
bool descending;
octave_idx_type n;
/* Identify next run. */
n = count_run (data + lo, nremaining, descending, comp);
if (n < 0)
goto fail;
if (descending)
{
std::reverse (data + lo, data + lo + n);
std::reverse (idx + lo, idx + lo + n);
}
/* If short, extend to min (minrun, nremaining). */
if (n < minrun)
{
const octave_idx_type force = nremaining <= minrun ? nremaining
: minrun;
binarysort (data + lo, idx + lo, force, n, comp);
n = force;
}
/* Push run onto pending-runs stack, and maybe merge. */
assert (ms->n < MAX_MERGE_PENDING);
ms->pending[ms->n].base = lo;
ms->pending[ms->n].len = n;
ms->n++;
if (merge_collapse (data, idx, comp) < 0)
goto fail;
/* Advance to find next run. */
lo += n;
nremaining -= n;
}
while (nremaining);
merge_force_collapse (data, idx, comp);
}
fail:
return;
}
template <class T>
void
octave_sort<T>::sort (T *data, octave_idx_type nel)
{
#ifdef INLINE_ASCENDING_SORT
if (compare == ascending_compare)
sort (data, nel, std::less<T> ());
else
#endif
#ifdef INLINE_DESCENDING_SORT
if (compare == descending_compare)
sort (data, nel, std::greater<T> ());
else
#endif
if (compare)
sort (data, nel, compare);
}
template <class T>
void
octave_sort<T>::sort (T *data, octave_idx_type *idx, octave_idx_type nel)
{
#ifdef INLINE_ASCENDING_SORT
if (compare == ascending_compare)
sort (data, idx, nel, std::less<T> ());
else
#endif
#ifdef INLINE_DESCENDING_SORT
if (compare == descending_compare)
sort (data, idx, nel, std::greater<T> ());
else
#endif
if (compare)
sort (data, idx, nel, compare);
}
template <class T> template <class Comp>
bool
octave_sort<T>::is_sorted (const T *data, octave_idx_type nel, Comp comp)
{
const T *end = data + nel;
if (data != end)
{
const T *next = data;
while (++next != end)
{
if (comp (*next, *data))
break;
data = next;
}
data = next;
}
return data == end;
}
template <class T>
bool
octave_sort<T>::is_sorted (const T *data, octave_idx_type nel)
{
bool retval = false;
#ifdef INLINE_ASCENDING_SORT
if (compare == ascending_compare)
retval = is_sorted (data, nel, std::less<T> ());
else
#endif
#ifdef INLINE_DESCENDING_SORT
if (compare == descending_compare)
retval = is_sorted (data, nel, std::greater<T> ());
else
#endif
if (compare)
retval = is_sorted (data, nel, compare);
return retval;
}
// FIXME: is there really no way to make this local to the following function?
struct sortrows_run_t
{
sortrows_run_t (octave_idx_type c, octave_idx_type o, octave_idx_type n)
: col (c), ofs (o), nel (n) { }
octave_idx_type col, ofs, nel;
};
template <class T> template <class Comp>
void
octave_sort<T>::sort_rows (const T *data, octave_idx_type *idx,
octave_idx_type rows, octave_idx_type cols,
Comp comp)
{
OCTAVE_LOCAL_BUFFER (T, buf, rows);
for (octave_idx_type i = 0; i < rows; i++)
idx[i] = i;
if (cols == 0 || rows <= 1)
return;
// This is a breadth-first traversal.
typedef sortrows_run_t run_t;
std::stack<run_t> runs;
runs.push (run_t (0, 0, rows));
while (! runs.empty ())
{
octave_idx_type col = runs.top ().col;
octave_idx_type ofs = runs.top ().ofs;
octave_idx_type nel = runs.top ().nel;
runs.pop ();
assert (nel > 1);
T *lbuf = buf + ofs;
const T *ldata = data + rows*col;
octave_idx_type *lidx = idx + ofs;
// Gather.
for (octave_idx_type i = 0; i < nel; i++)
lbuf[i] = ldata[lidx[i]];
// Sort.
sort (lbuf, lidx, nel, comp);
// Identify constant runs and schedule subsorts.
if (col < cols-1)
{
octave_idx_type lst = 0;
for (octave_idx_type i = 0; i < nel; i++)
{
if (comp (lbuf[lst], lbuf[i]))
{
if (i > lst + 1)
runs.push (run_t (col+1, ofs + lst, i - lst));
lst = i;
}
}
if (nel > lst + 1)
runs.push (run_t (col+1, ofs + lst, nel - lst));
}
}
}
template <class T>
void
octave_sort<T>::sort_rows (const T *data, octave_idx_type *idx,
octave_idx_type rows, octave_idx_type cols)
{
#ifdef INLINE_ASCENDING_SORT
if (compare == ascending_compare)
sort_rows (data, idx, rows, cols, std::less<T> ());
else
#endif
#ifdef INLINE_DESCENDING_SORT
if (compare == descending_compare)
sort_rows (data, idx, rows, cols, std::greater<T> ());
else
#endif
if (compare)
sort_rows (data, idx, rows, cols, compare);
}
template <class T> template <class Comp>
bool
octave_sort<T>::is_sorted_rows (const T *data, octave_idx_type rows,
octave_idx_type cols, Comp comp)
{
if (rows <= 1 || cols == 0)
return true;
// This is a breadth-first traversal.
const T *lastrow = data + rows*(cols - 1);
typedef std::pair<const T *, octave_idx_type> run_t;
std::stack<run_t> runs;
bool sorted = true;
runs.push (run_t (data, rows));
while (sorted && ! runs.empty ())
{
const T *lo = runs.top ().first;
octave_idx_type n = runs.top ().second;
runs.pop ();
if (lo < lastrow)
{
// Not the final column.
assert (n > 1);
const T *hi = lo + n, *lst = lo;
for (lo++; lo < hi; lo++)
{
if (comp (*lst, *lo))
{
if (lo > lst + 1)
runs.push (run_t (lst + rows, lo - lst));
lst = lo;
}
else if (comp (*lo, *lst))
break;
}
if (lo == hi)
{
if (lo > lst + 1)
runs.push (run_t (lst + rows, lo - lst));
}
else
{
sorted = false;
break;
}
}
else
// The final column - use fast code.
sorted = is_sorted (lo, n, comp);
}
return sorted;
}
template <class T>
bool
octave_sort<T>::is_sorted_rows (const T *data, octave_idx_type rows,
octave_idx_type cols)
{
bool retval = false;
#ifdef INLINE_ASCENDING_SORT
if (compare == ascending_compare)
retval = is_sorted_rows (data, rows, cols, std::less<T> ());
else
#endif
#ifdef INLINE_DESCENDING_SORT
if (compare == descending_compare)
retval = is_sorted_rows (data, rows, cols, std::greater<T> ());
else
#endif
if (compare)
retval = is_sorted_rows (data, rows, cols, compare);
return retval;
}
// The simple binary lookup.
template <class T> template <class Comp>
octave_idx_type
octave_sort<T>::lookup (const T *data, octave_idx_type nel,
const T& value, Comp comp)
{
octave_idx_type lo = 0, hi = nel;
while (lo < hi)
{
octave_idx_type mid = lo + ((hi-lo) >> 1);
if (comp (value, data[mid]))
hi = mid;
else
lo = mid + 1;
}
return lo;
}
template <class T>
octave_idx_type
octave_sort<T>::lookup (const T *data, octave_idx_type nel,
const T& value)
{
octave_idx_type retval = 0;
#ifdef INLINE_ASCENDING_SORT
if (compare == ascending_compare)
retval = lookup (data, nel, value, std::less<T> ());
else
#endif
#ifdef INLINE_DESCENDING_SORT
if (compare == descending_compare)
retval = lookup (data, nel, value, std::greater<T> ());
else
#endif
if (compare)
retval = lookup (data, nel, value, std::ptr_fun (compare));
return retval;
}
template <class T> template <class Comp>
void
octave_sort<T>::lookup (const T *data, octave_idx_type nel,
const T *values, octave_idx_type nvalues,
octave_idx_type *idx, Comp comp)
{
// Use a sequence of binary lookups.
// TODO: Can this be sped up generally? The sorted merge case is dealt with
// elsewhere.
for (octave_idx_type j = 0; j < nvalues; j++)
idx[j] = lookup (data, nel, values[j], comp);
}
template <class T>
void
octave_sort<T>::lookup (const T *data, octave_idx_type nel,
const T* values, octave_idx_type nvalues,
octave_idx_type *idx)
{
#ifdef INLINE_ASCENDING_SORT
if (compare == ascending_compare)
lookup (data, nel, values, nvalues, idx, std::less<T> ());
else
#endif
#ifdef INLINE_DESCENDING_SORT
if (compare == descending_compare)
lookup (data, nel, values, nvalues, idx, std::greater<T> ());
else
#endif
if (compare)
lookup (data, nel, values, nvalues, idx, std::ptr_fun (compare));
}
template <class T> template <class Comp>
void
octave_sort<T>::lookup_sorted (const T *data, octave_idx_type nel,
const T *values, octave_idx_type nvalues,
octave_idx_type *idx, bool rev, Comp comp)
{
if (rev)
{
octave_idx_type i = 0, j = nvalues - 1;
if (nvalues > 0 && nel > 0)
{
while (true)
{
if (comp (values[j], data[i]))
{
idx[j] = i;
if (--j < 0)
break;
}
else if (++i == nel)
break;
}
}
for (; j >= 0; j--)
idx[j] = i;
}
else
{
octave_idx_type i = 0, j = 0;
if (nvalues > 0 && nel > 0)
{
while (true)
{
if (comp (values[j], data[i]))
{
idx[j] = i;
if (++j == nvalues)
break;
}
else if (++i == nel)
break;
}
}
for (; j != nvalues; j++)
idx[j] = i;
}
}
template <class T>
void
octave_sort<T>::lookup_sorted (const T *data, octave_idx_type nel,
const T* values, octave_idx_type nvalues,
octave_idx_type *idx, bool rev)
{
#ifdef INLINE_ASCENDING_SORT
if (compare == ascending_compare)
lookup_sorted (data, nel, values, nvalues, idx, rev, std::less<T> ());
else
#endif
#ifdef INLINE_DESCENDING_SORT
if (compare == descending_compare)
lookup_sorted (data, nel, values, nvalues, idx, rev, std::greater<T> ());
else
#endif
if (compare)
lookup_sorted (data, nel, values, nvalues, idx, rev,
std::ptr_fun (compare));
}
template <class T> template <class Comp>
void
octave_sort<T>::nth_element (T *data, octave_idx_type nel,
octave_idx_type lo, octave_idx_type up,
Comp comp)
{
// Simply wrap the STL algorithms.
// FIXME: this will fail if we attempt to inline <,> for Complex.
if (up == lo+1)
std::nth_element (data, data + lo, data + nel, comp);
else if (lo == 0)
std::partial_sort (data, data + up, data + nel, comp);
else
{
std::nth_element (data, data + lo, data + nel, comp);
if (up == lo + 2)
{
// Finding two subsequent elements.
std::swap (data[lo+1],
*std::min_element (data + lo + 1, data + nel, comp));
}
else
std::partial_sort (data + lo + 1, data + up, data + nel, comp);
}
}
template <class T>
void
octave_sort<T>::nth_element (T *data, octave_idx_type nel,
octave_idx_type lo, octave_idx_type up)
{
if (up < 0)
up = lo + 1;
#ifdef INLINE_ASCENDING_SORT
if (compare == ascending_compare)
nth_element (data, nel, lo, up, std::less<T> ());
else
#endif
#ifdef INLINE_DESCENDING_SORT
if (compare == descending_compare)
nth_element (data, nel, lo, up, std::greater<T> ());
else
#endif
if (compare)
nth_element (data, nel, lo, up, std::ptr_fun (compare));
}
template <class T>
bool
octave_sort<T>::ascending_compare (typename ref_param<T>::type x,
typename ref_param<T>::type y)
{
return x < y;
}
template <class T>
bool
octave_sort<T>::descending_compare (typename ref_param<T>::type x,
typename ref_param<T>::type y)
{
return x > y;
}
|