-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabsurd_bubble_sort.js
52 lines (45 loc) · 1.25 KB
/
absurd_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
var readline = require("readline");
var reader = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function askIfGreaterThan(el1, el2, callback) {
reader.question("Is " + el1 + " greater than " + el2 + " ?", function (answer) {
if (answer === 'yes') {
callback(true);
} else {
callback(false);
}
});
};
function innerBubbleSortLoop(arr, i, madeAnySwaps, outerBubbleSortLoop) {
if (i == arr.length - 1) {
outerBubbleSortLoop(madeAnySwaps);
} else {
askIfGreaterThan(arr[i], arr[i+1], function(boolean) {
if (boolean === true) {
var store = arr[i];
arr[i] = arr[i+1];
arr[i+1] = store;
madeAnySwaps = true
}
innerBubbleSortLoop(arr, i + 1, madeAnySwaps, outerBubbleSortLoop)
});
}
};
function absurdBubbleSort (arr, sortCompletionCallback) {
function outerBubbleSortLoop(madeAnySwaps){
if (madeAnySwaps) {
innerBubbleSortLoop(arr, 0, false, outerBubbleSortLoop)
} else {
sortCompletionCallback(arr);
}
}
var madeAnySwaps = true;
outerBubbleSortLoop(madeAnySwaps);
}
absurdBubbleSort([3,2,1], function (arr) {
console.log("Sorted array: " + JSON.stringify(arr));
reader.close();
});
console.log("Last program line");