|
1 | 1 | logger._print('original array = [' + D.join(', ') + ']'); |
2 | 2 |
|
3 | | -function quicksort(low, high) { |
4 | | - if (low < high) { |
5 | | - var p = partition(low, high); |
6 | | - quicksort(low, p - 1); |
7 | | - quicksort(p + 1, high); |
8 | | - } |
9 | | -} |
10 | | - |
11 | | -function partition(low, high) { |
12 | | - var pivot = D[high]; |
13 | | - tracer._select(low, high); |
14 | | - var i = low; |
15 | | - var temp; |
16 | | - |
17 | | - for (var j = low; j < high; j++) { |
18 | | - if (D[j] <= pivot) { |
19 | | - temp = D[i]; |
| 3 | +function partition(D, low, high) { |
| 4 | + var i, j, s; |
| 5 | + while (high > low) { |
| 6 | + i = low; |
| 7 | + j = high; |
| 8 | + s = D[low]; |
| 9 | + while (i < j) { |
| 10 | + tracer._select(high)._select(low)._wait(); |
| 11 | + while (D[j] > s){ |
| 12 | + tracer._select(j)._wait(); |
| 13 | + tracer._deselect(j); |
| 14 | + j--; |
| 15 | + } |
20 | 16 | D[i] = D[j]; |
21 | | - D[j] = temp; |
22 | | - tracer._notify(i, D[i])._notify(j, D[j])._wait(); |
23 | | - tracer._denotify(i)._denotify(j); |
24 | | - i++; |
| 17 | + tracer._notify(i, D[j])._wait()._denotify(i); |
| 18 | + while (s >= D[i] && i < j){ |
| 19 | + tracer._select(i)._wait(); |
| 20 | + tracer._deselect(i); |
| 21 | + i++; |
| 22 | + } |
| 23 | + D[j] = D[i]; |
| 24 | + tracer._notify(j, D[i])._wait()._denotify(j); |
| 25 | + tracer._deselect(high)._deselect(low); |
25 | 26 | } |
| 27 | + D[i] = s; |
| 28 | + tracer._notify(i, s)._wait(); |
| 29 | + tracer._denotify(i); |
| 30 | + partition(D, low, i-1); |
| 31 | + low = i+1; |
26 | 32 | } |
27 | | - temp = D[i]; |
28 | | - D[i] = D[high]; |
29 | | - D[high] = temp; |
30 | | - tracer._notify(i, D[i])._notify(high, D[high])._wait(); |
31 | | - tracer._denotify(i)._denotify(high); |
32 | | - tracer._deselect(low, high); |
33 | | - return i; |
34 | 33 | } |
35 | 34 |
|
36 | | -quicksort(0, D.length - 1); |
| 35 | +function quicksort(D) { |
| 36 | + partition(D, 0, D.length-1); |
| 37 | +} |
| 38 | + |
| 39 | +quicksort(D); |
37 | 40 | logger._print('sorted array = [' + D.join(', ') + ']'); |
0 commit comments