Files
JavaScript/Sorts/QuickSort.js
Sukhpreet K Sekhon 6c2f83b752 Add doctest for QuickSort and MergeSort (#502)
* Add doctest for QuickSort

* Add doctest for MergeSort

Co-authored-by: Sukhpreet Sekhon <ssekhon@atb.com>
2020-10-24 21:03:55 +05:30

52 lines
920 B
JavaScript

/*
* Quick sort is a comparison sorting algorithm that uses a divide and conquer strategy.
* For more information see here: https://en.wikipedia.org/wiki/Quicksort
*/
/*
* Doctests
*
* > quickSort([5, 4, 3, 10, 2, 1])
* [1, 2, 3, 4, 5, 10]
* > quickSort([])
* []
* > quickSort([5, 4])
* [4, 5]
* > quickSort([1, 2, 3])
* [1, 2, 3]
*/
function quickSort (items) {
var length = items.length
if (length <= 1) {
return items
}
var PIVOT = items[0]
var GREATER = []
var LESSER = []
for (var i = 1; i < length; i++) {
if (items[i] > PIVOT) {
GREATER.push(items[i])
} else {
LESSER.push(items[i])
}
}
var sorted = quickSort(LESSER)
sorted.push(PIVOT)
sorted = sorted.concat(quickSort(GREATER))
return sorted
}
// Implementation of quick sort
var ar = [0, 5, 3, 2, 2]
// Array before Sort
console.log(ar)
ar = quickSort(ar)
// Array after sort
console.log(ar)