Skip to content

Commit 89f4b75

Browse files
committed
Sorting visualization & new quicksort
1 parent f96db70 commit 89f4b75

File tree

2 files changed

+34
-29
lines changed

2 files changed

+34
-29
lines changed

algorithm/sorting/bubble/basic/code.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ do {
55
swapped = false;
66
tracer._select(N - 1)._wait();
77
for (var i = 1; i < N; i++) {
8+
tracer._select(i)._wait();
89
if (D[i - 1] > D[i]) {
910
logger._print('swap ' + D[i - 1] + ' and ' + D[i]);
1011
var temp = D[i - 1];
@@ -14,6 +15,7 @@ do {
1415
tracer._notify(i - 1, D[i - 1])._notify(i, D[i])._wait();
1516
tracer._denotify(i - 1)._denotify(i);
1617
}
18+
tracer._deselect(i);
1719
}
1820
tracer._deselect(N - 1);
1921
N--;
Lines changed: 32 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,40 @@
11
logger._print('original array = [' + D.join(', ') + ']');
22

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+
}
2016
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);
2526
}
27+
D[i] = s;
28+
tracer._notify(i, s)._wait();
29+
tracer._denotify(i);
30+
partition(D, low, i-1);
31+
low = i+1;
2632
}
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;
3433
}
3534

36-
quicksort(0, D.length - 1);
35+
function quicksort(D) {
36+
partition(D, 0, D.length-1);
37+
}
38+
39+
quicksort(D);
3740
logger._print('sorted array = [' + D.join(', ') + ']');

0 commit comments

Comments
 (0)