-
Notifications
You must be signed in to change notification settings - Fork 1
/
bubblesort.js
53 lines (44 loc) · 925 Bytes
/
bubblesort.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
function swap(num){
num++;
return num;
}
// function comparisonCount(num){
// totalSwap += num;
// return totalSwap;
// }
function bubbleSort(arr) {
var swapCount = 0;
var totalSwap = 0;
if (arr.length === 0 || arr.length === 1) {
return arr;
}
for (var i = 0; i < arr.length - 1; i++){
if (arr[i] > arr[i+1]){
var temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
swapCount = swap(swapCount);
}
}
// totalSwap = comparisonCount(swapCount);
if (swapCount === 0) {
return arr
} else {
return bubbleSort(arr)
}
}
// function BubbleSort(arr){
// var swap = true;
// while (swap === true){
// swap = false;
// for (var i = 0; i < arr.length - 1; i++){
// if (arr[i] > arr[i+1]){
// var temp = arr[i];
// arr[i] = arr[i+1];
// arr[i+1] = temp;
// swap = true;
// }
// }
// }
// return arr;
// }