JSFiddle - React, Tailwind, and code Playground

by sramnan

JavaScript

function swap(items,i,j){
var temp = items[j];
items[j] = items[i];
items[i] = temp;
}
function partition(items, left, right) {
  pivot = items[Math.floor(left + right / 2)];
  console.log(pivot);
  i = left;
  j = right;
  while (i <= j) {
    if (items[i] < pivot) {
      i++;
    }
    if (items[j] > pivot) {
      j--;
    }
    if(i<=j){
    swap(items,i,j);
    i++;
    j--;
    }
  }
  return i;
}


function quickSort(items, left, right) {
  var index;
  if (items.length > 1) {
  left = typeof(left) !=  "number"? 0 : left;
  right = typeof(right) !=  "number" ? 0 : right;
  index = partition(items, left, right);
  if(left < index - 1){
  quicksort(items,left,index -1);
  }
  if(right > index){
    quicksort(items,index,right);
  }
  }
  return items;
}
console.log(quickSort([4,6,5]));