# JavaScript Quick Sort

Posted on: July 10, 2017

Quick sort divide the array in multiple sequence, hence is a very good candidate for recursivity. The asymptotic analysis gives a `O(log(n^2))`

in average and a worse time of `O(n^2)`

. The algorithm can be implemented in different flavor depending of where you start the initial pivot. Then, there is a second way to customize the quick sort and it's by defining how we partition.

1function swap(array, left, right) {2 var temp = array[left];3 array[left] = array[right];4 array[right] = temp;5}67function partition(arrayToSort, left, right) {8 var i = left;9 var j = right;10 var pivot = arrayToSort[Math.floor((left + right) / 2)]; // Middle1112 while (i <= j) {13 while (arrayToSort[i] < pivot) {14 i++;15 }16 while (arrayToSort[j] > pivot) {17 j--;18 }19 if (i <= j) {20 swap(arrayToSort, i, j);21 i++;22 j--;23 }24 }2526 return i;27}2829function quickSort(arrayToSort, left, right) {30 var index = partition(arrayToSort, left, right);31 if (left < index - 1) {32 quickSort(arrayToSort, left, index - 1);33 }34 if (right > index) {35 quickSort(arrayToSort, index, right);36 }37}

The algorithm divide the array in two (pivot) and go to each extremity of a partition which is between left to right where left or right is determined by the pivot. Most of the heavy-lifting is done by the partition function that will swap element if this one found that a number at the right of the pivot is bigger than one of the left side of the pivot. The algorithm goes from swap until the two extremity touch and then move back to the other side of the partition. Every call to quickSort function bring a new partition which divide the array in smaller and smaller array to partition.

The choice of the pivot will change the way the algorithm performs. The most in the middle, the best it is. This is something that we cannot know since this would require to traverse the whole array. This is why we can randomly choose a value, or in that case, taking the element in the middle.

The partition goal is to ensure that everything before the pivot is smaller than the pivot. By going recursively, at some point everything is sorted.