-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort.js
More file actions
25 lines (23 loc) · 731 Bytes
/
quickSort.js
File metadata and controls
25 lines (23 loc) · 731 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Quick array sorting
* @param {Array} array Source array
* @returns {Array} Sorted array
*/
function quicksort(array) {
//base case, array with 0 or 1 element are already sorted
if (array.length < 2) return array;
// recursive case
let pivot = array[0];
// partitioning the lefts arrays.
// sub-arrays of all the elements less than the pivot
let less = array.slice(1).filter((element) => {
return element <= pivot;
})
//sub-array of all the elements greater than the pivot
let greater = array.slice(1).filter((element) => {
return element > pivot;
})
return quicksort(less).concat([pivot], quicksort(greater));
}
let numbersArray = [2, 5, 7, 4, 9, 1];
console.log(quicksort(numbersArray))