|
| 1 | +var items = [5,3,7,6,2,9]; |
| 2 | +function swap(items, leftIndex, rightIndex){ |
| 3 | + var temp = items[leftIndex]; |
| 4 | + items[leftIndex] = items[rightIndex]; |
| 5 | + items[rightIndex] = temp; |
| 6 | +} |
| 7 | +function 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 | + |
| 27 | +function 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 |
| 41 | +var sortedArray = quickSort(items, 0, items.length - 1); |
| 42 | +console.log(sortedArray); //prints [2,3,5,6,7,9] |
0 commit comments