-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubble-sort.js
58 lines (53 loc) · 1.47 KB
/
bubble-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
var n = 30;
function randomSizedBar() {
var w = Math.floor(Math.random()*500);
var $bar = $("<div>"+w+"</div>");
$bar.addClass("bar");
$bar.css("width", w);
$bar.value=w;
return ($bar);
};
function swapElementsOfClass(classType, index1, index2) {
if(index2 < index1) {
var temp = index1;
index1 = index2;
index2 = temp;
}
$($(classType)[index1]).before($(classType)[index2]);
$($(classType)[index2]).after($(classType)[index1+1]);
//if(index1) {
// setInterval(swapElementsOfClass, 500, classType, index1, index2);
// }
//setTimeout(swapElementsOfClass, 500);
};
function bubbleSort(nodeLocation) {
var elementArray = $(nodeLocation);
var n = elementArray.length;
var wasSwapped = true;
while(wasSwapped) {
wasSwapped = false;
for(var i=n-1; i>0; i--) {
if(Number($(elementArray[i]).text()) < Number($(elementArray[i-1]).text())) {
//setTimeout(function() {
swapElementsOfClass(elementArray, i, i-1);//},500);
elementArray = $(nodeLocation);
wasSwapped = true;
};
};
};
};
function initializeDiagram(nodeLocation) {
for(var i=0; i<n; i++) {
$(nodeLocation).append(randomSizedBar());
}
}
$(function() {
initializeDiagram('#sorting-animation');
$('#start-button').on('click', function() {
bubbleSort('#sorting-animation div');
});
$('#randomize-button').on('click', function() {
$('#sorting-animation').empty();
initializeDiagram('#sorting-animation');
});
});