|
1 | 1 | function swap(items, leftIndex, rightIndex){
|
2 |
| - var temp = items[leftIndex]; |
3 |
| - items[leftIndex] = items[rightIndex]; |
4 |
| - items[rightIndex] = temp; |
| 2 | + var temp = items[leftIndex]; |
| 3 | + items[leftIndex] = items[rightIndex]; |
| 4 | + items[rightIndex] = temp; |
5 | 5 | }
|
6 | 6 | function partition(items, left, right) {
|
7 |
| - var pivot = items[Math.floor((right + left) / 2)], //middle element |
8 |
| - i = left, //left pointer |
9 |
| - j = right; //right pointer |
10 |
| - while (i <= j) { |
11 |
| - while (items[i] < pivot) { |
12 |
| - i++; |
13 |
| - } |
14 |
| - while (items[j] > pivot) { |
15 |
| - j--; |
16 |
| - } |
17 |
| - if (i <= j) { |
18 |
| - swap(items, i, j); //sawpping two elements |
19 |
| - i++; |
20 |
| - j--; |
21 |
| - } |
| 7 | + var pivot = items[Math.floor((right + left) / 2)], //middle element |
| 8 | + i = left, //left pointer |
| 9 | + j = right; //right pointer |
| 10 | + while (i <= j) { |
| 11 | + while (items[i] < pivot) { |
| 12 | + i++; |
22 | 13 | }
|
23 |
| - return i; |
| 14 | + while (items[j] > pivot) { |
| 15 | + j--; |
| 16 | + } |
| 17 | + if (i <= j) { |
| 18 | + swap(items, i, j); //sawpping two elements |
| 19 | + i++; |
| 20 | + j--; |
| 21 | + } |
| 22 | + } |
| 23 | + return i; |
24 | 24 | }
|
25 | 25 |
|
26 | 26 | function quickSort(items, left, right) {
|
27 |
| - var index; |
28 |
| - if (items.length > 1) { |
29 |
| - index = partition(items, left, right); //index returned from partition |
30 |
| - if (left < index - 1) { //more elements on the left side of the pivot |
31 |
| - quickSort(items, left, index - 1); |
32 |
| - } |
33 |
| - if (index < right) { //more elements on the right side of the pivot |
34 |
| - quickSort(items, index, right); |
35 |
| - } |
| 27 | + var index; |
| 28 | + if (items.length > 1) { |
| 29 | + index = partition(items, left, right); //index returned from partition |
| 30 | + if (left < index - 1) { //more elements on the left side of the pivot |
| 31 | + quickSort(items, left, index - 1); |
| 32 | + } |
| 33 | + if (index < right) { //more elements on the right side of the pivot |
| 34 | + quickSort(items, index, right); |
36 | 35 | }
|
37 |
| - return items; |
| 36 | + } |
| 37 | + return items; |
38 | 38 | }
|
39 | 39 |
|
| 40 | +module.exports.quickSort = quickSort; |
0 commit comments