-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubbleSort.js
30 lines (27 loc) · 918 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
/**
* Bubble sort algorithm implemented on arrays for numbers
*/
function bubbleSort(unsortedArray_, comparisonFunction) {
const unsortedArray = [...unsortedArray_];
let swape = false;
for(let i=0; i<unsortedArray.length; i++) {
swape = false;
for(let j=0; j<unsortedArray.length - i; j++) {
if(comparisonFunction(unsortedArray[j], unsortedArray[j+1]) >= 0) {
[unsortedArray[j], unsortedArray[j+1]] = [unsortedArray[j+1], unsortedArray[j]];
swape = true;
}
}
}
if(!swape) { return unsortedArray; }
}
function comparator(a, b) {
if(a == b) return 0;
if(a < b) return 1;
if(a > b) return -1;
// return a == b ? 0 : (a > b ? 1 : -1 );
}
let unsortedArray = [ 1, 5, 3, 77, 3];
let sortedArray = bubbleSort(unsortedArray, comparator);
console.log(sortedArray);
// console.log(typeof(comparator(1, 1)))