Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Quicksort

 

 

How it works
  1. Quicksort starts iteration by Picking a Pivot element,
  2. Pivot can be chosen from the:
  3. The first element of an array or
  4. Last element of an array or
  5. The middle element of an array or
  6. Any random element of an array,
  7. It follows the principle of divide and conquers methodology,
  8. Means breaking array into a group of smaller array called a partition process,
Process
  1. Placing all smaller element than pivot element into the left side of pivot element,
  2. Placing all greater element than pivot element into the right side of pivot element,
  3. Recursively applies same for separately on subarray of the left side of pivot element and subarray of the right side of pivot element
Performance
  1. Best case perfoarmace: Time complexity O(n),
  2. Averagecase performance: Time complexity O(n log n),
  3. Worstcase performace: Time complexity O(n log n),
Implement QuickSort
Let’s implement the QuickSort in Javascript
function swap(array, leftPointer, rightPointer) {
  var temp = array[leftPointer];
  array[leftPointer] = array[rightPointer];
  array[rightPointer] = temp;
}
function subArrayPartition(array, left, right) {
  var pivot = array[Math.floor((right + left) / 2)],
    i = left, //left pointer
    j = right; //right pointer
  while (i <= j) {
    while (array[i] < pivot) {
      i++;
    }
    while (array[j] > pivot) {
      j--;
    }
    if (i <= j) {
      swap(array, i, j); //sawpping two elements
      i++;
      j--;
    }
  }
  return i;
}
function quickSort(array, lowerBound, upperBound) {
  var index;
  if (array.length > 1) {
    index = subArrayPartition(array, lowerBound, upperBound); //index returned from subArrayPartition
    if (lowerBound < index - 1) { //more elements on the lowerBound side of the pivot
      quickSort(array, lowerBound, index - 1);
    }
    if (index < upperBound) { //more elements on the upperBound side of the pivot
      quickSort(array, index, upperBound);
    }
  }
  return array;
}
// first call to quick sort
var array = [5, 3, 7, 6, 2, 9];
var sortedArray = quickSort(array, 0, array.length - 1);
console.log(sortedArray);

 

One thought on “Quicksort

Comments are closed.