1function quicksort(array) {
2 if (array.length <= 1) {
3 return array;
4 }
5
6 var pivot = array[0];
7
8 var left = [];
9 var right = [];
10
11 for (var i = 1; i < array.length; i++) {
12 array[i] < pivot ? left.push(array[i]) : right.push(array[i]);
13 }
14
15 return quicksort(left).concat(pivot, quicksort(right));
16};
1const quickSort = array =>
2 (function qsort(arr, start, end) {
3 if (start >= end) return arr;
4 let swapPos = start;
5
6 for (let i = start; i <= end; i++) {
7 if (arr[i] <= arr[end]) {
8 [arr[swapPos], arr[i]] = [arr[i], arr[swapPos]];
9 swapPos++;
10 }
11 }
12 qsort(arr, start, --swapPos - 1);
13 qsort(arr, swapPos + 1, end);
14
15 return arr;
16 })(Array.from(array), 0, array.length - 1);
1var items = [5, 3, 7, 6, 2, 9];
2
3function swap(items, leftIndex, rightIndex) {
4 var temp = items[leftIndex];
5 items[leftIndex] = items[rightIndex];
6 items[rightIndex] = temp;
7}
8
9function partition(items, left, right) {
10 var pivot = items[Math.floor((right + left) / 2)], //middle element
11 i = left, //left pointer
12 j = right; //right pointer
13 while (i <= j) {
14 while (items[i] < pivot) {
15 i++;
16 }
17 while (items[j] > pivot) {
18 j--;
19 }
20 if (i <= j) {
21 swap(items, i, j); //sawpping two elements
22 i++;
23 j--;
24 }
25 }
26 return i;
27}
28
29function quickSort(items, left, right) {
30 var index;
31 if (items.length > 1) {
32 index = partition(items, left, right); //index returned from partition
33 if (left < index - 1) {
34 //more elements on the left side of the pivot
35 quickSort(items, left, index - 1);
36 }
37 if (index < right) {
38 //more elements on the right side of the pivot
39 quickSort(items, index, right);
40 }
41 }
42 return items;
43}
44
45// first call to quick sort
46var sortedArray = quickSort(items, 0, items.length - 1);
47console.log(sortedArray); //prints [2,3,5,6,7,9]
1var items = [5,3,7,6,2,9];
2function swap(items, leftIndex, rightIndex){
3 var temp = items[leftIndex];
4 items[leftIndex] = items[rightIndex];
5 items[rightIndex] = temp;
6}
7function partition(items, left, right) {
8 var pivot = items[Math.floor((right + left) / 2)], //middle element
9 i = left, //left pointer
10 j = right; //right pointer
11 while (i <= j) {
12 while (items[i] < pivot) {
13 i++;
14 }
15 while (items[j] > pivot) {
16 j--;
17 }
18 if (i <= j) {
19 swap(items, i, j); //sawpping two elements
20 i++;
21 j--;
22 }
23 }
24 return i;
25}
26
27function quickSort(items, left, right) {
28 var index;
29 if (items.length > 1) {
30 index = partition(items, left, right); //index returned from partition
31 if (left < index - 1) { //more elements on the left side of the pivot
32 quickSort(items, left, index - 1);
33 }
34 if (index < right) { //more elements on the right side of the pivot
35 quickSort(items, index, right);
36 }
37 }
38 return items;
39}
40// first call to quick sort
41var sortedArray = quickSort(items, 0, items.length - 1);
42console.log(sortedArray); //prints [2,3,5,6,7,9]
43