-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathbubble_sort.js
44 lines (38 loc) · 1.18 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
/*
Bubble Sort to sort elements in array in ascending order
*/
function bubbleSortAscending(array) {
// Loop for each array index
for (let i = 0; i < array.length; i++) {
// for each inner loop completion the largest number is bubbled out to end
for (let j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
// if ith elemenet is larger than i+1th swap the two
let temporary = array[j];
array[j] = array[j + 1];
array[j + 1] = temporary;
}
}
}
return array;
}
console.log(bubbleSortAscending([3, 5, 1, 11, 4, 1, 21, 19, 17, 6]));
/*
Sort in descending order
*/
function bubbleSortDescending(array) {
// Loop for each array index
for (let i = 0; i < array.length; i++) {
// for each inner loop completion the largest number is bubbled out to end
for (let j = 0; j < array.length - 1 - i; j++) {
if (array[j] < array[j + 1]) {
// if ith elemenet is larger than i+1th swap the two
let temporary = array[j];
array[j] = array[j + 1];
array[j + 1] = temporary;
}
}
}
return array;
}
console.log(bubbleSortDescending([3, 5, 1, 11, 4, 1, 21, 19, 17, 6]));