-
Notifications
You must be signed in to change notification settings - Fork 1
/
bubble-sort.js
35 lines (30 loc) · 1.01 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
// impelmenting bubble sort algorithms
function bubbleSortByDescending(arr = []) {
if (!Array.isArray(arr)) throw new Error("argument must be array");
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (typeof arr[i] !== "number")
throw new Error("array must be array of numbers");
if (arr[i] < arr[j]) {
[arr[i], arr[j]] = [arr[j], arr[i]]; //swap operations
}
}
}
return arr;
}
function bubbleSortByAscending(arr) {
if (!Array.isArray(arr)) throw new Error("argument must be array");
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (typeof arr[i] !== "number")
throw new Error("array must be array of numbers");
if (arr[i] > arr[j]) {
[arr[i], arr[j]] = [arr[j], arr[i]]; //swap operations
}
}
}
return arr;
}
// test both bubble sort
console.log(bubbleSortByAscending([3, 46, 4, 6, 1, 7, 5]));
console.log(bubbleSortByDescending([3, 46, 4, 6, 2, 7, 5]));