-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap_sort.js
93 lines (70 loc) · 2.18 KB
/
heap_sort.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
function Heap()
{
//Setting Time complexities
document.getElementById("Time_Worst").innerText="O(N log N)";
document.getElementById("Time_Average").innerText="Θ(N log N)";
document.getElementById("Time_Best").innerText="Ω(N log N)";
//Setting Space complexity
document.getElementById("Space_Worst").innerText="O(1)";
c_delay=0;
heap_sort();
enable_buttons();
}
function swap(i,j)
{
div_update(divs[i],div_sizes[i],"red");//Color update
div_update(divs[j],div_sizes[j],"red");//Color update
var temp=div_sizes[i];
div_sizes[i]=div_sizes[j];
div_sizes[j]=temp;
div_update(divs[i],div_sizes[i],"red");//Height update
div_update(divs[j],div_sizes[j],"red");//Height update
div_update(divs[i],div_sizes[i],"blue");//Color update
div_update(divs[j],div_sizes[j],"blue");//Color update
}
function max_heapify(n,i)
{
var largest=i;
var l=2*i+1;
var r=2*i+2;
if(l<n && div_sizes[l]>div_sizes[largest])
{
if(largest!=i)
{
div_update(divs[largest],div_sizes[largest],"blue");//Color update
}
largest=l;
div_update(divs[largest],div_sizes[largest],"red");//Color update
}
if(r<n && div_sizes[r]>div_sizes[largest])
{
if(largest!=i)
{
div_update(divs[largest],div_sizes[largest],"blue");//Color update
}
largest=r;
div_update(divs[largest],div_sizes[largest],"red");//Color update
}
if(largest!=i)
{
swap(i,largest);
max_heapify(n,largest);
}
}
function heap_sort()
{
for(var i=Math.floor(array_size/2)-1;i>=0;i--)
{
max_heapify(array_size,i);
}
for(var i=array_size-1;i>0;i--)
{
swap(0,i);
div_update(divs[i],div_sizes[i],"green");//Color update
div_update(divs[i],div_sizes[i],"yellow");//Color update
max_heapify(i,0);
div_update(divs[i],div_sizes[i],"blue");//Color update
div_update(divs[i],div_sizes[i],"green");//Color update
}
div_update(divs[i],div_sizes[i],"green");//Color update
}