bzlib_blocksort.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. /*-------------------------------------------------------------*/
  2. /*--- Block sorting machinery ---*/
  3. /*--- blocksort.c ---*/
  4. /*-------------------------------------------------------------*/
  5. /*--
  6. This file is a part of bzip2 and/or libbzip2, a program and
  7. library for lossless, block-sorting data compression.
  8. Copyright (C) 1996-2002 Julian R Seward. All rights reserved.
  9. Redistribution and use in source and binary forms, with or without
  10. modification, are permitted provided that the following conditions
  11. are met:
  12. 1. Redistributions of source code must retain the above copyright
  13. notice, this list of conditions and the following disclaimer.
  14. 2. The origin of this software must not be misrepresented; you must
  15. not claim that you wrote the original software. If you use this
  16. software in a product, an acknowledgment in the product
  17. documentation would be appreciated but is not required.
  18. 3. Altered source versions must be plainly marked as such, and must
  19. not be misrepresented as being the original software.
  20. 4. The name of the author may not be used to endorse or promote
  21. products derived from this software without specific prior written
  22. permission.
  23. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
  24. OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  25. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  26. ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  27. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  28. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  29. GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  30. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  31. WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  32. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  33. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34. Julian Seward, Cambridge, UK.
  35. jseward@acm.org
  36. bzip2/libbzip2 version 1.0.6 of 6 September 2010
  37. Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>
  38. This program is based on (at least) the work of:
  39. Mike Burrows
  40. David Wheeler
  41. Peter Fenwick
  42. Alistair Moffat
  43. Radford Neal
  44. Ian H. Witten
  45. Robert Sedgewick
  46. Jon L. Bentley
  47. For more information on these sources, see the manual.
  48. --*/
  49. #include "bzlib_private.h"
  50. /*---------------------------------------------*/
  51. /*--- Fallback O(N log(N)^2) sorting ---*/
  52. /*--- algorithm, for repetitive blocks ---*/
  53. /*---------------------------------------------*/
  54. /*---------------------------------------------*/
  55. static
  56. __inline__
  57. void fallbackSimpleSort ( UInt32* fmap,
  58. UInt32* eclass,
  59. Int32 lo,
  60. Int32 hi )
  61. {
  62. Int32 i, j, tmp;
  63. UInt32 ec_tmp;
  64. if (lo == hi) return;
  65. if (hi - lo > 3) {
  66. for ( i = hi-4; i >= lo; i-- ) {
  67. tmp = fmap[i];
  68. ec_tmp = eclass[tmp];
  69. for ( j = i+4; j <= hi && ec_tmp > eclass[fmap[j]]; j += 4 )
  70. fmap[j-4] = fmap[j];
  71. fmap[j-4] = tmp;
  72. }
  73. }
  74. for ( i = hi-1; i >= lo; i-- ) {
  75. tmp = fmap[i];
  76. ec_tmp = eclass[tmp];
  77. for ( j = i+1; j <= hi && ec_tmp > eclass[fmap[j]]; j++ )
  78. fmap[j-1] = fmap[j];
  79. fmap[j-1] = tmp;
  80. }
  81. }
  82. /*---------------------------------------------*/
  83. #define fswap(zz1, zz2) \
  84. { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; }
  85. #define fvswap(zzp1, zzp2, zzn) \
  86. { \
  87. Int32 yyp1 = (zzp1); \
  88. Int32 yyp2 = (zzp2); \
  89. Int32 yyn = (zzn); \
  90. while (yyn > 0) { \
  91. fswap(fmap[yyp1], fmap[yyp2]); \
  92. yyp1++; yyp2++; yyn--; \
  93. } \
  94. }
  95. #define fmin(a,b) ((a) < (b)) ? (a) : (b)
  96. #define fpush(lz,hz) { stackLo[sp] = lz; \
  97. stackHi[sp] = hz; \
  98. sp++; }
  99. #define fpop(lz,hz) { sp--; \
  100. lz = stackLo[sp]; \
  101. hz = stackHi[sp]; }
  102. #define FALLBACK_QSORT_SMALL_THRESH 10
  103. #define FALLBACK_QSORT_STACK_SIZE 100
  104. static
  105. void fallbackQSort3 ( UInt32* fmap,
  106. UInt32* eclass,
  107. Int32 loSt,
  108. Int32 hiSt )
  109. {
  110. Int32 unLo, unHi, ltLo, gtHi, n, m;
  111. Int32 sp, lo, hi;
  112. UInt32 med, r, r3;
  113. Int32 stackLo[FALLBACK_QSORT_STACK_SIZE];
  114. Int32 stackHi[FALLBACK_QSORT_STACK_SIZE];
  115. r = 0;
  116. sp = 0;
  117. fpush ( loSt, hiSt );
  118. while (sp > 0) {
  119. AssertH ( sp < FALLBACK_QSORT_STACK_SIZE - 1, 1004 );
  120. fpop ( lo, hi );
  121. if (hi - lo < FALLBACK_QSORT_SMALL_THRESH) {
  122. fallbackSimpleSort ( fmap, eclass, lo, hi );
  123. continue;
  124. }
  125. /* Random partitioning. Median of 3 sometimes fails to
  126. avoid bad cases. Median of 9 seems to help but
  127. looks rather expensive. This too seems to work but
  128. is cheaper. Guidance for the magic constants
  129. 7621 and 32768 is taken from Sedgewick's algorithms
  130. book, chapter 35.
  131. */
  132. r = ((r * 7621) + 1) % 32768;
  133. r3 = r % 3;
  134. if (r3 == 0) med = eclass[fmap[lo]]; else
  135. if (r3 == 1) med = eclass[fmap[(lo+hi)>>1]]; else
  136. med = eclass[fmap[hi]];
  137. unLo = ltLo = lo;
  138. unHi = gtHi = hi;
  139. while (1) {
  140. while (1) {
  141. if (unLo > unHi) break;
  142. n = (Int32)eclass[fmap[unLo]] - (Int32)med;
  143. if (n == 0) {
  144. fswap(fmap[unLo], fmap[ltLo]);
  145. ltLo++; unLo++;
  146. continue;
  147. };
  148. if (n > 0) break;
  149. unLo++;
  150. }
  151. while (1) {
  152. if (unLo > unHi) break;
  153. n = (Int32)eclass[fmap[unHi]] - (Int32)med;
  154. if (n == 0) {
  155. fswap(fmap[unHi], fmap[gtHi]);
  156. gtHi--; unHi--;
  157. continue;
  158. };
  159. if (n < 0) break;
  160. unHi--;
  161. }
  162. if (unLo > unHi) break;
  163. fswap(fmap[unLo], fmap[unHi]); unLo++; unHi--;
  164. }
  165. AssertD ( unHi == unLo-1, "fallbackQSort3(2)" );
  166. if (gtHi < ltLo) continue;
  167. n = fmin(ltLo-lo, unLo-ltLo); fvswap(lo, unLo-n, n);
  168. m = fmin(hi-gtHi, gtHi-unHi); fvswap(unLo, hi-m+1, m);
  169. n = lo + unLo - ltLo - 1;
  170. m = hi - (gtHi - unHi) + 1;
  171. if (n - lo > hi - m) {
  172. fpush ( lo, n );
  173. fpush ( m, hi );
  174. } else {
  175. fpush ( m, hi );
  176. fpush ( lo, n );
  177. }
  178. }
  179. }
  180. #undef fmin
  181. #undef fpush
  182. #undef fpop
  183. #undef fswap
  184. #undef fvswap
  185. #undef FALLBACK_QSORT_SMALL_THRESH
  186. #undef FALLBACK_QSORT_STACK_SIZE
  187. /*---------------------------------------------*/
  188. /* Pre:
  189. nblock > 0
  190. eclass exists for [0 .. nblock-1]
  191. ((UChar*)eclass) [0 .. nblock-1] holds block
  192. ptr exists for [0 .. nblock-1]
  193. Post:
  194. ((UChar*)eclass) [0 .. nblock-1] holds block
  195. All other areas of eclass destroyed
  196. fmap [0 .. nblock-1] holds sorted order
  197. bhtab [ 0 .. 2+(nblock/32) ] destroyed
  198. */
  199. #define SET_BH(zz) bhtab[(zz) >> 5] |= (1 << ((zz) & 31))
  200. #define CLEAR_BH(zz) bhtab[(zz) >> 5] &= ~(1 << ((zz) & 31))
  201. #define ISSET_BH(zz) (bhtab[(zz) >> 5] & (1 << ((zz) & 31)))
  202. #define WORD_BH(zz) bhtab[(zz) >> 5]
  203. #define UNALIGNED_BH(zz) ((zz) & 0x01f)
  204. static
  205. void fallbackSort ( UInt32* fmap,
  206. UInt32* eclass,
  207. UInt32* bhtab,
  208. Int32 nblock,
  209. Int32 verb )
  210. {
  211. Int32 ftab[257];
  212. Int32 ftabCopy[256];
  213. Int32 H, i, j, k, l, r, cc, cc1;
  214. Int32 nNotDone;
  215. Int32 nBhtab;
  216. UChar* eclass8 = (UChar*)eclass;
  217. /*--
  218. Initial 1-char radix sort to generate
  219. initial fmap and initial BH bits.
  220. --*/
  221. if (verb >= 4)
  222. VPrintf0 ( " bucket sorting ...\n" );
  223. for (i = 0; i < 257; i++) ftab[i] = 0;
  224. for (i = 0; i < nblock; i++) ftab[eclass8[i]]++;
  225. for (i = 0; i < 256; i++) ftabCopy[i] = ftab[i];
  226. for (i = 1; i < 257; i++) ftab[i] += ftab[i-1];
  227. for (i = 0; i < nblock; i++) {
  228. j = eclass8[i];
  229. k = ftab[j] - 1;
  230. ftab[j] = k;
  231. fmap[k] = i;
  232. }
  233. nBhtab = 2 + (nblock / 32);
  234. for (i = 0; i < nBhtab; i++) bhtab[i] = 0;
  235. for (i = 0; i < 256; i++) SET_BH(ftab[i]);
  236. /*--
  237. Inductively refine the buckets. Kind-of an
  238. "exponential radix sort" (!), inspired by the
  239. Manber-Myers suffix array construction algorithm.
  240. --*/
  241. /*-- set sentinel bits for block-end detection --*/
  242. for (i = 0; i < 32; i++) {
  243. SET_BH(nblock + 2*i);
  244. CLEAR_BH(nblock + 2*i + 1);
  245. }
  246. /*-- the log(N) loop --*/
  247. H = 1;
  248. while (1) {
  249. if (verb >= 4)
  250. VPrintf1 ( " depth %6d has ", H );
  251. j = 0;
  252. for (i = 0; i < nblock; i++) {
  253. if (ISSET_BH(i)) j = i;
  254. k = fmap[i] - H; if (k < 0) k += nblock;
  255. eclass[k] = j;
  256. }
  257. nNotDone = 0;
  258. r = -1;
  259. while (1) {
  260. /*-- find the next non-singleton bucket --*/
  261. k = r + 1;
  262. while (ISSET_BH(k) && UNALIGNED_BH(k)) k++;
  263. if (ISSET_BH(k)) {
  264. while (WORD_BH(k) == 0xffffffff) k += 32;
  265. while (ISSET_BH(k)) k++;
  266. }
  267. l = k - 1;
  268. if (l >= nblock) break;
  269. while (!ISSET_BH(k) && UNALIGNED_BH(k)) k++;
  270. if (!ISSET_BH(k)) {
  271. while (WORD_BH(k) == 0x00000000) k += 32;
  272. while (!ISSET_BH(k)) k++;
  273. }
  274. r = k - 1;
  275. if (r >= nblock) break;
  276. /*-- now [l, r] bracket current bucket --*/
  277. if (r > l) {
  278. nNotDone += (r - l + 1);
  279. fallbackQSort3 ( fmap, eclass, l, r );
  280. /*-- scan bucket and generate header bits-- */
  281. cc = -1;
  282. for (i = l; i <= r; i++) {
  283. cc1 = eclass[fmap[i]];
  284. if (cc != cc1) { SET_BH(i); cc = cc1; };
  285. }
  286. }
  287. }
  288. if (verb >= 4)
  289. VPrintf1 ( "%6d unresolved strings\n", nNotDone );
  290. H *= 2;
  291. if (H > nblock || nNotDone == 0) break;
  292. }
  293. /*--
  294. Reconstruct the original block in
  295. eclass8 [0 .. nblock-1], since the
  296. previous phase destroyed it.
  297. --*/
  298. if (verb >= 4)
  299. VPrintf0 ( " reconstructing block ...\n" );
  300. j = 0;
  301. for (i = 0; i < nblock; i++) {
  302. while (ftabCopy[j] == 0) j++;
  303. ftabCopy[j]--;
  304. eclass8[fmap[i]] = (UChar)j;
  305. }
  306. AssertH ( j < 256, 1005 );
  307. }
  308. #undef SET_BH
  309. #undef CLEAR_BH
  310. #undef ISSET_BH
  311. #undef WORD_BH
  312. #undef UNALIGNED_BH
  313. /*---------------------------------------------*/
  314. /*--- The main, O(N^2 log(N)) sorting ---*/
  315. /*--- algorithm. Faster for "normal" ---*/
  316. /*--- non-repetitive blocks. ---*/
  317. /*---------------------------------------------*/
  318. /*---------------------------------------------*/
  319. static
  320. __inline__
  321. Bool mainGtU ( UInt32 i1,
  322. UInt32 i2,
  323. UChar* block,
  324. UInt16* quadrant,
  325. UInt32 nblock,
  326. Int32* budget )
  327. {
  328. Int32 k;
  329. UChar c1, c2;
  330. UInt16 s1, s2;
  331. AssertD ( i1 != i2, "mainGtU" );
  332. /* 1 */
  333. c1 = block[i1]; c2 = block[i2];
  334. if (c1 != c2) return (c1 > c2);
  335. i1++; i2++;
  336. /* 2 */
  337. c1 = block[i1]; c2 = block[i2];
  338. if (c1 != c2) return (c1 > c2);
  339. i1++; i2++;
  340. /* 3 */
  341. c1 = block[i1]; c2 = block[i2];
  342. if (c1 != c2) return (c1 > c2);
  343. i1++; i2++;
  344. /* 4 */
  345. c1 = block[i1]; c2 = block[i2];
  346. if (c1 != c2) return (c1 > c2);
  347. i1++; i2++;
  348. /* 5 */
  349. c1 = block[i1]; c2 = block[i2];
  350. if (c1 != c2) return (c1 > c2);
  351. i1++; i2++;
  352. /* 6 */
  353. c1 = block[i1]; c2 = block[i2];
  354. if (c1 != c2) return (c1 > c2);
  355. i1++; i2++;
  356. /* 7 */
  357. c1 = block[i1]; c2 = block[i2];
  358. if (c1 != c2) return (c1 > c2);
  359. i1++; i2++;
  360. /* 8 */
  361. c1 = block[i1]; c2 = block[i2];
  362. if (c1 != c2) return (c1 > c2);
  363. i1++; i2++;
  364. /* 9 */
  365. c1 = block[i1]; c2 = block[i2];
  366. if (c1 != c2) return (c1 > c2);
  367. i1++; i2++;
  368. /* 10 */
  369. c1 = block[i1]; c2 = block[i2];
  370. if (c1 != c2) return (c1 > c2);
  371. i1++; i2++;
  372. /* 11 */
  373. c1 = block[i1]; c2 = block[i2];
  374. if (c1 != c2) return (c1 > c2);
  375. i1++; i2++;
  376. /* 12 */
  377. c1 = block[i1]; c2 = block[i2];
  378. if (c1 != c2) return (c1 > c2);
  379. i1++; i2++;
  380. k = nblock + 8;
  381. do {
  382. /* 1 */
  383. c1 = block[i1]; c2 = block[i2];
  384. if (c1 != c2) return (c1 > c2);
  385. s1 = quadrant[i1]; s2 = quadrant[i2];
  386. if (s1 != s2) return (s1 > s2);
  387. i1++; i2++;
  388. /* 2 */
  389. c1 = block[i1]; c2 = block[i2];
  390. if (c1 != c2) return (c1 > c2);
  391. s1 = quadrant[i1]; s2 = quadrant[i2];
  392. if (s1 != s2) return (s1 > s2);
  393. i1++; i2++;
  394. /* 3 */
  395. c1 = block[i1]; c2 = block[i2];
  396. if (c1 != c2) return (c1 > c2);
  397. s1 = quadrant[i1]; s2 = quadrant[i2];
  398. if (s1 != s2) return (s1 > s2);
  399. i1++; i2++;
  400. /* 4 */
  401. c1 = block[i1]; c2 = block[i2];
  402. if (c1 != c2) return (c1 > c2);
  403. s1 = quadrant[i1]; s2 = quadrant[i2];
  404. if (s1 != s2) return (s1 > s2);
  405. i1++; i2++;
  406. /* 5 */
  407. c1 = block[i1]; c2 = block[i2];
  408. if (c1 != c2) return (c1 > c2);
  409. s1 = quadrant[i1]; s2 = quadrant[i2];
  410. if (s1 != s2) return (s1 > s2);
  411. i1++; i2++;
  412. /* 6 */
  413. c1 = block[i1]; c2 = block[i2];
  414. if (c1 != c2) return (c1 > c2);
  415. s1 = quadrant[i1]; s2 = quadrant[i2];
  416. if (s1 != s2) return (s1 > s2);
  417. i1++; i2++;
  418. /* 7 */
  419. c1 = block[i1]; c2 = block[i2];
  420. if (c1 != c2) return (c1 > c2);
  421. s1 = quadrant[i1]; s2 = quadrant[i2];
  422. if (s1 != s2) return (s1 > s2);
  423. i1++; i2++;
  424. /* 8 */
  425. c1 = block[i1]; c2 = block[i2];
  426. if (c1 != c2) return (c1 > c2);
  427. s1 = quadrant[i1]; s2 = quadrant[i2];
  428. if (s1 != s2) return (s1 > s2);
  429. i1++; i2++;
  430. if (i1 >= nblock) i1 -= nblock;
  431. if (i2 >= nblock) i2 -= nblock;
  432. k -= 8;
  433. (*budget)--;
  434. }
  435. while (k >= 0);
  436. return False;
  437. }
  438. /*---------------------------------------------*/
  439. /*--
  440. Knuth's increments seem to work better
  441. than Incerpi-Sedgewick here. Possibly
  442. because the number of elems to sort is
  443. usually small, typically <= 20.
  444. --*/
  445. static
  446. Int32 incs[14] = { 1, 4, 13, 40, 121, 364, 1093, 3280,
  447. 9841, 29524, 88573, 265720,
  448. 797161, 2391484 };
  449. static
  450. void mainSimpleSort ( UInt32* ptr,
  451. UChar* block,
  452. UInt16* quadrant,
  453. Int32 nblock,
  454. Int32 lo,
  455. Int32 hi,
  456. Int32 d,
  457. Int32* budget )
  458. {
  459. Int32 i, j, h, bigN, hp;
  460. UInt32 v;
  461. bigN = hi - lo + 1;
  462. if (bigN < 2) return;
  463. hp = 0;
  464. while (incs[hp] < bigN) hp++;
  465. hp--;
  466. for (; hp >= 0; hp--) {
  467. h = incs[hp];
  468. i = lo + h;
  469. while (True) {
  470. /*-- copy 1 --*/
  471. if (i > hi) break;
  472. v = ptr[i];
  473. j = i;
  474. while ( mainGtU (
  475. ptr[j-h]+d, v+d, block, quadrant, nblock, budget
  476. ) ) {
  477. ptr[j] = ptr[j-h];
  478. j = j - h;
  479. if (j <= (lo + h - 1)) break;
  480. }
  481. ptr[j] = v;
  482. i++;
  483. /*-- copy 2 --*/
  484. if (i > hi) break;
  485. v = ptr[i];
  486. j = i;
  487. while ( mainGtU (
  488. ptr[j-h]+d, v+d, block, quadrant, nblock, budget
  489. ) ) {
  490. ptr[j] = ptr[j-h];
  491. j = j - h;
  492. if (j <= (lo + h - 1)) break;
  493. }
  494. ptr[j] = v;
  495. i++;
  496. /*-- copy 3 --*/
  497. if (i > hi) break;
  498. v = ptr[i];
  499. j = i;
  500. while ( mainGtU (
  501. ptr[j-h]+d, v+d, block, quadrant, nblock, budget
  502. ) ) {
  503. ptr[j] = ptr[j-h];
  504. j = j - h;
  505. if (j <= (lo + h - 1)) break;
  506. }
  507. ptr[j] = v;
  508. i++;
  509. if (*budget < 0) return;
  510. }
  511. }
  512. }
  513. /*---------------------------------------------*/
  514. /*--
  515. The following is an implementation of
  516. an elegant 3-way quicksort for strings,
  517. described in a paper "Fast Algorithms for
  518. Sorting and Searching Strings", by Robert
  519. Sedgewick and Jon L. Bentley.
  520. --*/
  521. #define mswap(zz1, zz2) \
  522. { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; }
  523. #define mvswap(zzp1, zzp2, zzn) \
  524. { \
  525. Int32 yyp1 = (zzp1); \
  526. Int32 yyp2 = (zzp2); \
  527. Int32 yyn = (zzn); \
  528. while (yyn > 0) { \
  529. mswap(ptr[yyp1], ptr[yyp2]); \
  530. yyp1++; yyp2++; yyn--; \
  531. } \
  532. }
  533. static
  534. __inline__
  535. UChar mmed3 ( UChar a, UChar b, UChar c )
  536. {
  537. UChar t;
  538. if (a > b) { t = a; a = b; b = t; };
  539. if (b > c) {
  540. b = c;
  541. if (a > b) b = a;
  542. }
  543. return b;
  544. }
  545. #define mmin(a,b) ((a) < (b)) ? (a) : (b)
  546. #define mpush(lz,hz,dz) { stackLo[sp] = lz; \
  547. stackHi[sp] = hz; \
  548. stackD [sp] = dz; \
  549. sp++; }
  550. #define mpop(lz,hz,dz) { sp--; \
  551. lz = stackLo[sp]; \
  552. hz = stackHi[sp]; \
  553. dz = stackD [sp]; }
  554. #define mnextsize(az) (nextHi[az]-nextLo[az])
  555. #define mnextswap(az,bz) \
  556. { Int32 tz; \
  557. tz = nextLo[az]; nextLo[az] = nextLo[bz]; nextLo[bz] = tz; \
  558. tz = nextHi[az]; nextHi[az] = nextHi[bz]; nextHi[bz] = tz; \
  559. tz = nextD [az]; nextD [az] = nextD [bz]; nextD [bz] = tz; }
  560. #define MAIN_QSORT_SMALL_THRESH 20
  561. #define MAIN_QSORT_DEPTH_THRESH (BZ_N_RADIX + BZ_N_QSORT)
  562. #define MAIN_QSORT_STACK_SIZE 100
  563. static
  564. void mainQSort3 ( UInt32* ptr,
  565. UChar* block,
  566. UInt16* quadrant,
  567. Int32 nblock,
  568. Int32 loSt,
  569. Int32 hiSt,
  570. Int32 dSt,
  571. Int32* budget )
  572. {
  573. Int32 unLo, unHi, ltLo, gtHi, n, m, med;
  574. Int32 sp, lo, hi, d;
  575. Int32 stackLo[MAIN_QSORT_STACK_SIZE];
  576. Int32 stackHi[MAIN_QSORT_STACK_SIZE];
  577. Int32 stackD [MAIN_QSORT_STACK_SIZE];
  578. Int32 nextLo[3];
  579. Int32 nextHi[3];
  580. Int32 nextD [3];
  581. sp = 0;
  582. mpush ( loSt, hiSt, dSt );
  583. while (sp > 0) {
  584. AssertH ( sp < MAIN_QSORT_STACK_SIZE - 2, 1001 );
  585. mpop ( lo, hi, d );
  586. if (hi - lo < MAIN_QSORT_SMALL_THRESH ||
  587. d > MAIN_QSORT_DEPTH_THRESH) {
  588. mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget );
  589. if (*budget < 0) return;
  590. continue;
  591. }
  592. med = (Int32)
  593. mmed3 ( block[ptr[ lo ]+d],
  594. block[ptr[ hi ]+d],
  595. block[ptr[ (lo+hi)>>1 ]+d] );
  596. unLo = ltLo = lo;
  597. unHi = gtHi = hi;
  598. while (True) {
  599. while (True) {
  600. if (unLo > unHi) break;
  601. n = ((Int32)block[ptr[unLo]+d]) - med;
  602. if (n == 0) {
  603. mswap(ptr[unLo], ptr[ltLo]);
  604. ltLo++; unLo++; continue;
  605. };
  606. if (n > 0) break;
  607. unLo++;
  608. }
  609. while (True) {
  610. if (unLo > unHi) break;
  611. n = ((Int32)block[ptr[unHi]+d]) - med;
  612. if (n == 0) {
  613. mswap(ptr[unHi], ptr[gtHi]);
  614. gtHi--; unHi--; continue;
  615. };
  616. if (n < 0) break;
  617. unHi--;
  618. }
  619. if (unLo > unHi) break;
  620. mswap(ptr[unLo], ptr[unHi]); unLo++; unHi--;
  621. }
  622. AssertD ( unHi == unLo-1, "mainQSort3(2)" );
  623. if (gtHi < ltLo) {
  624. mpush(lo, hi, d+1 );
  625. continue;
  626. }
  627. n = mmin(ltLo-lo, unLo-ltLo); mvswap(lo, unLo-n, n);
  628. m = mmin(hi-gtHi, gtHi-unHi); mvswap(unLo, hi-m+1, m);
  629. n = lo + unLo - ltLo - 1;
  630. m = hi - (gtHi - unHi) + 1;
  631. nextLo[0] = lo; nextHi[0] = n; nextD[0] = d;
  632. nextLo[1] = m; nextHi[1] = hi; nextD[1] = d;
  633. nextLo[2] = n+1; nextHi[2] = m-1; nextD[2] = d+1;
  634. if (mnextsize(0) < mnextsize(1)) mnextswap(0,1);
  635. if (mnextsize(1) < mnextsize(2)) mnextswap(1,2);
  636. if (mnextsize(0) < mnextsize(1)) mnextswap(0,1);
  637. AssertD (mnextsize(0) >= mnextsize(1), "mainQSort3(8)" );
  638. AssertD (mnextsize(1) >= mnextsize(2), "mainQSort3(9)" );
  639. mpush (nextLo[0], nextHi[0], nextD[0]);
  640. mpush (nextLo[1], nextHi[1], nextD[1]);
  641. mpush (nextLo[2], nextHi[2], nextD[2]);
  642. }
  643. }
  644. #undef mswap
  645. #undef mvswap
  646. #undef mpush
  647. #undef mpop
  648. #undef mmin
  649. #undef mnextsize
  650. #undef mnextswap
  651. #undef MAIN_QSORT_SMALL_THRESH
  652. #undef MAIN_QSORT_DEPTH_THRESH
  653. #undef MAIN_QSORT_STACK_SIZE
  654. /*---------------------------------------------*/
  655. /* Pre:
  656. nblock > N_OVERSHOOT
  657. block32 exists for [0 .. nblock-1 +N_OVERSHOOT]
  658. ((UChar*)block32) [0 .. nblock-1] holds block
  659. ptr exists for [0 .. nblock-1]
  660. Post:
  661. ((UChar*)block32) [0 .. nblock-1] holds block
  662. All other areas of block32 destroyed
  663. ftab [0 .. 65536 ] destroyed
  664. ptr [0 .. nblock-1] holds sorted order
  665. if (*budget < 0), sorting was abandoned
  666. */
  667. #define BIGFREQ(b) (ftab[((b)+1) << 8] - ftab[(b) << 8])
  668. #define SETMASK (1 << 21)
  669. #define CLEARMASK (~(SETMASK))
  670. static
  671. void mainSort ( UInt32* ptr,
  672. UChar* block,
  673. UInt16* quadrant,
  674. UInt32* ftab,
  675. Int32 nblock,
  676. Int32 verb,
  677. Int32* budget )
  678. {
  679. Int32 i, j, k, ss, sb;
  680. Int32 runningOrder[256];
  681. Bool bigDone[256];
  682. Int32 copyStart[256];
  683. Int32 copyEnd [256];
  684. UChar c1;
  685. Int32 numQSorted;
  686. UInt16 s;
  687. if (verb >= 4) VPrintf0 ( " main sort initialise ...\n" );
  688. /*-- set up the 2-byte frequency table --*/
  689. for (i = 65536; i >= 0; i--) ftab[i] = 0;
  690. j = block[0] << 8;
  691. i = nblock-1;
  692. for (; i >= 3; i -= 4) {
  693. quadrant[i] = 0;
  694. j = (j >> 8) | ( ((UInt16)block[i]) << 8);
  695. ftab[j]++;
  696. quadrant[i-1] = 0;
  697. j = (j >> 8) | ( ((UInt16)block[i-1]) << 8);
  698. ftab[j]++;
  699. quadrant[i-2] = 0;
  700. j = (j >> 8) | ( ((UInt16)block[i-2]) << 8);
  701. ftab[j]++;
  702. quadrant[i-3] = 0;
  703. j = (j >> 8) | ( ((UInt16)block[i-3]) << 8);
  704. ftab[j]++;
  705. }
  706. for (; i >= 0; i--) {
  707. quadrant[i] = 0;
  708. j = (j >> 8) | ( ((UInt16)block[i]) << 8);
  709. ftab[j]++;
  710. }
  711. /*-- (emphasises close relationship of block & quadrant) --*/
  712. for (i = 0; i < BZ_N_OVERSHOOT; i++) {
  713. block [nblock+i] = block[i];
  714. quadrant[nblock+i] = 0;
  715. }
  716. if (verb >= 4) VPrintf0 ( " bucket sorting ...\n" );
  717. /*-- Complete the initial radix sort --*/
  718. for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1];
  719. s = block[0] << 8;
  720. i = nblock-1;
  721. for (; i >= 3; i -= 4) {
  722. s = (s >> 8) | (block[i] << 8);
  723. j = ftab[s] -1;
  724. ftab[s] = j;
  725. ptr[j] = i;
  726. s = (s >> 8) | (block[i-1] << 8);
  727. j = ftab[s] -1;
  728. ftab[s] = j;
  729. ptr[j] = i-1;
  730. s = (s >> 8) | (block[i-2] << 8);
  731. j = ftab[s] -1;
  732. ftab[s] = j;
  733. ptr[j] = i-2;
  734. s = (s >> 8) | (block[i-3] << 8);
  735. j = ftab[s] -1;
  736. ftab[s] = j;
  737. ptr[j] = i-3;
  738. }
  739. for (; i >= 0; i--) {
  740. s = (s >> 8) | (block[i] << 8);
  741. j = ftab[s] -1;
  742. ftab[s] = j;
  743. ptr[j] = i;
  744. }
  745. /*--
  746. Now ftab contains the first loc of every small bucket.
  747. Calculate the running order, from smallest to largest
  748. big bucket.
  749. --*/
  750. for (i = 0; i <= 255; i++) {
  751. bigDone [i] = False;
  752. runningOrder[i] = i;
  753. }
  754. {
  755. Int32 vv;
  756. Int32 h = 1;
  757. do h = 3 * h + 1; while (h <= 256);
  758. do {
  759. h = h / 3;
  760. for (i = h; i <= 255; i++) {
  761. vv = runningOrder[i];
  762. j = i;
  763. while ( BIGFREQ(runningOrder[j-h]) > BIGFREQ(vv) ) {
  764. runningOrder[j] = runningOrder[j-h];
  765. j = j - h;
  766. if (j <= (h - 1)) goto zero;
  767. }
  768. zero:
  769. runningOrder[j] = vv;
  770. }
  771. } while (h != 1);
  772. }
  773. /*--
  774. The main sorting loop.
  775. --*/
  776. numQSorted = 0;
  777. for (i = 0; i <= 255; i++) {
  778. /*--
  779. Process big buckets, starting with the least full.
  780. Basically this is a 3-step process in which we call
  781. mainQSort3 to sort the small buckets [ss, j], but
  782. also make a big effort to avoid the calls if we can.
  783. --*/
  784. ss = runningOrder[i];
  785. /*--
  786. Step 1:
  787. Complete the big bucket [ss] by quicksorting
  788. any unsorted small buckets [ss, j], for j != ss.
  789. Hopefully previous pointer-scanning phases have already
  790. completed many of the small buckets [ss, j], so
  791. we don't have to sort them at all.
  792. --*/
  793. for (j = 0; j <= 255; j++) {
  794. if (j != ss) {
  795. sb = (ss << 8) + j;
  796. if ( ! (ftab[sb] & SETMASK) ) {
  797. Int32 lo = ftab[sb] & CLEARMASK;
  798. Int32 hi = (ftab[sb+1] & CLEARMASK) - 1;
  799. if (hi > lo) {
  800. if (verb >= 4)
  801. VPrintf4 ( " qsort [0x%x, 0x%x] "
  802. "done %d this %d\n",
  803. ss, j, numQSorted, hi - lo + 1 );
  804. mainQSort3 (
  805. ptr, block, quadrant, nblock,
  806. lo, hi, BZ_N_RADIX, budget
  807. );
  808. numQSorted += (hi - lo + 1);
  809. if (*budget < 0) return;
  810. }
  811. }
  812. ftab[sb] |= SETMASK;
  813. }
  814. }
  815. AssertH ( !bigDone[ss], 1006 );
  816. /*--
  817. Step 2:
  818. Now scan this big bucket [ss] so as to synthesise the
  819. sorted order for small buckets [t, ss] for all t,
  820. including, magically, the bucket [ss,ss] too.
  821. This will avoid doing Real Work in subsequent Step 1's.
  822. --*/
  823. {
  824. for (j = 0; j <= 255; j++) {
  825. copyStart[j] = ftab[(j << 8) + ss] & CLEARMASK;
  826. copyEnd [j] = (ftab[(j << 8) + ss + 1] & CLEARMASK) - 1;
  827. }
  828. for (j = ftab[ss << 8] & CLEARMASK; j < copyStart[ss]; j++) {
  829. k = ptr[j]-1; if (k < 0) k += nblock;
  830. c1 = block[k];
  831. if (!bigDone[c1])
  832. ptr[ copyStart[c1]++ ] = k;
  833. }
  834. for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) {
  835. k = ptr[j]-1; if (k < 0) k += nblock;
  836. c1 = block[k];
  837. if (!bigDone[c1])
  838. ptr[ copyEnd[c1]-- ] = k;
  839. }
  840. }
  841. AssertH ( (copyStart[ss]-1 == copyEnd[ss])
  842. ||
  843. /* Extremely rare case missing in bzip2-1.0.0 and 1.0.1.
  844. Necessity for this case is demonstrated by compressing
  845. a sequence of approximately 48.5 million of character
  846. 251; 1.0.0/1.0.1 will then die here. */
  847. (copyStart[ss] == 0 && copyEnd[ss] == nblock-1),
  848. 1007 )
  849. for (j = 0; j <= 255; j++) ftab[(j << 8) + ss] |= SETMASK;
  850. /*--
  851. Step 3:
  852. The [ss] big bucket is now done. Record this fact,
  853. and update the quadrant descriptors. Remember to
  854. update quadrants in the overshoot area too, if
  855. necessary. The "if (i < 255)" test merely skips
  856. this updating for the last bucket processed, since
  857. updating for the last bucket is pointless.
  858. The quadrant array provides a way to incrementally
  859. cache sort orderings, as they appear, so as to
  860. make subsequent comparisons in fullGtU() complete
  861. faster. For repetitive blocks this makes a big
  862. difference (but not big enough to be able to avoid
  863. the fallback sorting mechanism, exponential radix sort).
  864. The precise meaning is: at all times:
  865. for 0 <= i < nblock and 0 <= j <= nblock
  866. if block[i] != block[j],
  867. then the relative values of quadrant[i] and
  868. quadrant[j] are meaningless.
  869. else {
  870. if quadrant[i] < quadrant[j]
  871. then the string starting at i lexicographically
  872. precedes the string starting at j
  873. else if quadrant[i] > quadrant[j]
  874. then the string starting at j lexicographically
  875. precedes the string starting at i
  876. else
  877. the relative ordering of the strings starting
  878. at i and j has not yet been determined.
  879. }
  880. --*/
  881. bigDone[ss] = True;
  882. if (i < 255) {
  883. Int32 bbStart = ftab[ss << 8] & CLEARMASK;
  884. Int32 bbSize = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart;
  885. Int32 shifts = 0;
  886. while ((bbSize >> shifts) > 65534) shifts++;
  887. for (j = bbSize-1; j >= 0; j--) {
  888. Int32 a2update = ptr[bbStart + j];
  889. UInt16 qVal = (UInt16)(j >> shifts);
  890. quadrant[a2update] = qVal;
  891. if (a2update < BZ_N_OVERSHOOT)
  892. quadrant[a2update + nblock] = qVal;
  893. }
  894. AssertH ( ((bbSize-1) >> shifts) <= 65535, 1002 );
  895. }
  896. }
  897. if (verb >= 4)
  898. VPrintf3 ( " %d pointers, %d sorted, %d scanned\n",
  899. nblock, numQSorted, nblock - numQSorted );
  900. }
  901. #undef BIGFREQ
  902. #undef SETMASK
  903. #undef CLEARMASK
  904. /*---------------------------------------------*/
  905. /* Pre:
  906. nblock > 0
  907. arr2 exists for [0 .. nblock-1 +N_OVERSHOOT]
  908. ((UChar*)arr2) [0 .. nblock-1] holds block
  909. arr1 exists for [0 .. nblock-1]
  910. Post:
  911. ((UChar*)arr2) [0 .. nblock-1] holds block
  912. All other areas of block destroyed
  913. ftab [ 0 .. 65536 ] destroyed
  914. arr1 [0 .. nblock-1] holds sorted order
  915. */
  916. void BZ2_blockSort ( EState* s )
  917. {
  918. UInt32* ptr = s->ptr;
  919. UChar* block = s->block;
  920. UInt32* ftab = s->ftab;
  921. Int32 nblock = s->nblock;
  922. Int32 verb = s->verbosity;
  923. Int32 wfact = s->workFactor;
  924. UInt16* quadrant;
  925. Int32 budget;
  926. Int32 budgetInit;
  927. Int32 i;
  928. if (nblock < 10000) {
  929. fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb );
  930. } else {
  931. /* Calculate the location for quadrant, remembering to get
  932. the alignment right. Assumes that &(block[0]) is at least
  933. 2-byte aligned -- this should be ok since block is really
  934. the first section of arr2.
  935. */
  936. i = nblock+BZ_N_OVERSHOOT;
  937. if (i & 1) i++;
  938. quadrant = (UInt16*)(&(block[i]));
  939. /* (wfact-1) / 3 puts the default-factor-30
  940. transition point at very roughly the same place as
  941. with v0.1 and v0.9.0.
  942. Not that it particularly matters any more, since the
  943. resulting compressed stream is now the same regardless
  944. of whether or not we use the main sort or fallback sort.
  945. */
  946. if (wfact < 1 ) wfact = 1;
  947. if (wfact > 100) wfact = 100;
  948. budgetInit = nblock * ((wfact-1) / 3);
  949. budget = budgetInit;
  950. mainSort ( ptr, block, quadrant, ftab, nblock, verb, &budget );
  951. if (verb >= 3)
  952. VPrintf3 ( " %d work, %d block, ratio %5.2f\n",
  953. budgetInit - budget,
  954. nblock,
  955. (float)(budgetInit - budget) /
  956. (float)(nblock==0 ? 1 : nblock) );
  957. if (budget < 0) {
  958. if (verb >= 2)
  959. VPrintf0 ( " too repetitive; using fallback"
  960. " sorting algorithm\n" );
  961. fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb );
  962. }
  963. }
  964. s->origPtr = -1;
  965. for (i = 0; i < s->nblock; i++)
  966. if (ptr[i] == 0)
  967. { s->origPtr = i; break; };
  968. AssertH( s->origPtr != -1, 1003 );
  969. }
  970. /*-------------------------------------------------------------*/
  971. /*--- end blocksort.c ---*/
  972. /*-------------------------------------------------------------*/