-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathbubblesort.js
More file actions
46 lines (41 loc) · 1.28 KB
/
bubblesort.js
File metadata and controls
46 lines (41 loc) · 1.28 KB
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
45
46
const bubbleModule = () => {
const swap = (arr, i1, i2) => {
const tmp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = tmp;
return arr;
};
/*
* Bubble sort works in a nature similar to its name,
* the lesser - or lighter - values
* will 'bubble' to the beginning of the array,
* and the heavier values will 'sink'
* to the bottom.
*/
return {
bubbleSort: array => {
// create variables for swapping and our while loop condition
let swapped = true;
// Continue making passes until we have a clean pass with no swaps.
while (swapped) {
// init swapped to false at the top of the while loop
swapped = false;
// loop through our array
for (let i = 0; i < array.length; i++) {
// at each position, compare this element with the previous
// if this one is greater than our previous one swap it and
// flag our conditional to loop through our array again
if (array[i - 1] > array[i]) {
// swap the two numbers
swap(array, i - 1, i);
// flag our conditional to continue looping
swapped = true;
}
}
}
// return our sorted array
return array;
},
};
};
export default bubbleModule;