PageRenderTime 69ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/source/libs/bzlib/blocksort.c

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