aureooms/js-sort Home Manual Reference Source Test Repository

src/sort/fordjohnson.js

  1.  
  2. export function _fordjohnson ( binarysearch ) {
  3.  
  4. const fordjohnson = function ( compare , swap , a , i , j ) {
  5.  
  6. var m , k , t , y , p , q , r , x , l , w , s , pairswap ;
  7.  
  8. if ( j - i < 2 ) return ;
  9.  
  10. k = m = ( j - i ) / 2 | 0 ;
  11.  
  12. // compare pairs of elements and put largest elements at the front of the
  13. // array
  14.  
  15. while ( k-- ) {
  16.  
  17. if ( compare( a[i+k] , a[i+m+k] ) < 0 ) {
  18.  
  19. swap( a , i + k , i + m + k ) ;
  20.  
  21. }
  22.  
  23. }
  24.  
  25. // sort the largest elements at the front recursively
  26.  
  27. pairswap = function ( a , i , j ) {
  28. swap( a , i , j ) ;
  29. swap( a , i + m , j + m ) ;
  30. } ;
  31.  
  32. fordjohnson( compare , pairswap , a , i , i + m ) ;
  33.  
  34. // merge the rest of the array into the front, one item at a time
  35.  
  36. p = y = t = 1 ;
  37.  
  38. q = 0 ;
  39.  
  40. while ( i + m + t <= j ) {
  41.  
  42. r = t ;
  43.  
  44. while ( r --> q ) {
  45.  
  46. w = a[i+m+t-1] ;
  47.  
  48. x = binarysearch( compare , a , i , i + m + q , w ) ;
  49. l = x[0] + x[1] ;
  50.  
  51. s = i + m + t ;
  52.  
  53. while ( --s > l ) {
  54.  
  55. swap( a , s , s - 1 ) ;
  56.  
  57. }
  58.  
  59. }
  60.  
  61. q = t ;
  62.  
  63. p *= 2 ;
  64. y = p - 2 * t ;
  65. t += y ;
  66.  
  67. }
  68.  
  69. r = j - i - m ;
  70.  
  71. while ( r --> q ) {
  72.  
  73. w = a[j-1] ;
  74.  
  75. x = binarysearch( compare , a , i , i + m + q , w ) ;
  76. l = x[0] + x[1] ;
  77.  
  78. s = j ;
  79.  
  80. while ( --s > l ) {
  81.  
  82. swap( a , s , s - 1 ) ;
  83.  
  84. }
  85.  
  86.  
  87. }
  88.  
  89. } ;
  90.  
  91. return fordjohnson ;
  92.  
  93. }