Advertisement
binibiningtinamoran

Quicksort.js

May 27th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // QUICKSORT IMPLEMENTATION
  2.  
  3. function swap(items, leftIndex, rightIndex){
  4.     let temp = items[leftIndex];
  5.     items[leftIndex] = items[rightIndex];
  6.     items[rightIndex] = temp;
  7. }
  8.  
  9. function partition(items, left, right) {
  10.     let pivot   = items[Math.floor((right + left) / 2)], //middle element
  11.         i       = left, //left pointer
  12.         j       = right; //right pointer
  13.     while (i <= j) {
  14.         while (items[i] < pivot) {
  15.             i++;
  16.         }
  17.         while (items[j] > pivot) {
  18.             j--;
  19.         }
  20.         if (i <= j) {
  21.             swap(items, i, j); //sawpping two elements
  22.             i++;
  23.             j--;
  24.         }
  25.     }
  26.     return i;
  27. }
  28.  
  29. function quickSort(items, left, right) {
  30.     let index;
  31.     if (items.length > 1) {
  32.         index = partition(items, left, right); //index returned from partition
  33.         if (left < index - 1) { //more elements on the left side of the pivot
  34.             quickSort(items, left, index - 1);
  35.         }
  36.         if (index < right) { //more elements on the right side of the pivot
  37.             quickSort(items, index, right);
  38.         }
  39.     }
  40.     return items;
  41. }
  42.  
  43. let arr = [1,4,2,6,8,3,1,23,44,44,44];
  44. console.log(quickSort(arr, 0, arr.length-1));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement