-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbubblesort.js
More file actions
39 lines (32 loc) · 781 Bytes
/
bubblesort.js
File metadata and controls
39 lines (32 loc) · 781 Bytes
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
function swap(index1, index2, arr) {
let temp;
temp = arr[index2];
arr[index2] = arr[index1];
arr[index1] = temp;
return arr;
}
function compare(value1, value2) {
return value1 > value2;
}
function bubbleSort(array) {
let arr = array;
if (arr.length < 2) {
console.log(arr);
return arr;
} else {
let firstCompared = 0;
let lastCompared = arr.length + 1;
while (lastCompared > 0) {
for (let firstCompared = 0; firstCompared < lastCompared; firstCompared++) {
let value1 = arr[firstCompared];
let value2 = arr[firstCompared + 1];
if (compare(value1, value2)) {
arr = swap(firstCompared, firstCompared + 1, arr);
}
lastCompared--;
}
}
}
console.log(arr);
return arr;
}