-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbubbleSort.js
41 lines (35 loc) · 1.02 KB
/
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
///////// Bubble Sort: Implementation //////////
//////// for unsorted arrays /////////////
function bubbleSort(arr) {
for (let i = arr.length; i > 0; i--) {
for (let j = 0; j < i - 1; j++) {
// console.log(arr, arr[j], arr[j + 1]);
if (arr[j] > arr[j + 1]) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
console.log(bubbleSort([8, 61, 62, 36, 45, 5, 6, 7])); ///// [ 5, 6, 7, 8, 36, 45, 61, 62 ]
//////// for nearly sorted array optimized version with breake if no swaps ////////
function bubbleSort(arr) {
let noSwaps;
for (let i = arr.length; i > 0; i--) {
noSwaps = true;
for (let j = 0; j < i - 1; j++) {
// console.log(arr, arr[j], arr[j + 1]);
if (arr[j] > arr[j + 1]) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
noSwaps = false;
}
}
if (noSwaps) break;
}
return arr;
}
console.log(bubbleSort([8, 1, 2, 3, 4, 5, 6, 7])); // [ 1, 2, 3, 4, 5, 6, 7, 8 ]