Advertisement
rg443

quicksort_inplace

Jan 30th, 2013
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function quicksort_inplace(array) {
  2.     if(array.length < 2) return array;
  3.  
  4.     var starts = [0],
  5.         ends = [array.length - 1];
  6.  
  7.     while(starts.length > 0) {
  8.         var start = starts.pop(),
  9.             end = ends.pop(),
  10.             pivot = array[start],
  11.             storeIndex = start;
  12.  
  13.         // Move pivot to the end
  14.         array[start] = array[end];
  15.         array[end] = pivot;
  16.  
  17.         for (var currentIndex = start; currentIndex < end; currentIndex++) {
  18.             var swapVal = array[currentIndex];
  19.             if (swapVal < pivot) {
  20.                 array[currentIndex] = array[storeIndex];
  21.                 array[storeIndex] = swapVal;
  22.                 storeIndex++;
  23.             }
  24.         }
  25.  
  26.         // Move pivot back to the (new) pivot position
  27.         array[end] = array[storeIndex];
  28.         array[storeIndex] = pivot;
  29.  
  30.         if(end - storeIndex >= 2) {
  31.             starts.push(storeIndex + 1);
  32.             ends.push(end);
  33.         }
  34.  
  35.         if(storeIndex - start >= 2) {
  36.             starts.push(start);
  37.             ends.push(storeIndex - 1);
  38.         }
  39.     }
  40.     return array;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement