bzlib_blocksort.c 32 KB

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