-
Notifications
You must be signed in to change notification settings - Fork 0
/
quicksort.js
66 lines (53 loc) · 1.14 KB
/
quicksort.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
let arr = [];
function setup() {
createCanvas(400,400);
for(let i=0;i<40;i++)
{
arr[i] = int(random(2,height));
}
//print(arr.length)
quicksort(arr,0,arr.length-1);
}
async function quicksort(value,start,end)
{
if(start>=end)
return ;
let pivot=await partition(value,start,end);
await Promise.all([quicksort(value,pivot+1,end),
quicksort(value,start,pivot-1)]);
}
async function partition(value,start,end)
{
let pivot_value=value[end];
let pivot_ind=start;
for(let i=start;i<=end;i++)
{
if(value[i]<pivot_value)
{
await swap(value,i,pivot_ind);
pivot_ind++;
}
}
await swap(value,pivot_ind,end);
return pivot_ind;
}
async function swap(value,a,b)
{
print(a,b);
await sleep(100);
let temp = value[a];
value[a] = value[b];
value[b] = temp;
}
function draw()
{
background(0);
for(let i=0;i<arr.length;i++)
{
rect(i*10,height-arr[i],10,arr[i]);
}
print("draw",arr);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}