|
3 | 3 | * It has a running time of O(n²) in the worst case. |
4 | 4 | * It is used mostly when learning algorithms. |
5 | 5 | */ |
6 | | -const theArray = [72, 14, 34, 5, 24, 14, 53, 61, 38, 110, 39]; |
| 6 | +export default class BubbleSort { |
| 7 | + checkIfSwap(array, i, j) { |
| 8 | + let x = array[i]; |
| 9 | + let y = array[j]; |
7 | 10 |
|
8 | | -const checkIfSwap = (array, i, j) => { |
9 | | - x = array[i]; |
10 | | - y = array[j]; |
11 | | - |
12 | | - if (x > y) { |
13 | | - temp = x; |
14 | | - x = y; |
15 | | - array[i] = x; |
16 | | - array[j] = temp; |
17 | | - console.log(`Swapped! ${x} -> ${temp}`); |
| 11 | + if (x > y) { |
| 12 | + let temp = x; |
| 13 | + x = y; |
| 14 | + array[i] = x; |
| 15 | + array[j] = temp; |
| 16 | + console.log(`Swapped! ${x} -> ${temp}`); |
| 17 | + } |
18 | 18 | } |
19 | | -} |
20 | | -const bubbleSort = arrayToSort => { |
21 | | - const length = arrayToSort.length; |
22 | | - let temp, x, y; |
23 | 19 |
|
24 | | - for (var i = 0; i < length - 1; i++) { |
25 | | - console.log(`previous order: ${arrayToSort}`); |
| 20 | + sort(arrayToSort) { |
| 21 | + const length = arrayToSort.length; |
| 22 | + let temp, x, y; |
| 23 | + |
| 24 | + for (var i = 0; i < length - 1; i++) { |
| 25 | + console.log(`previous order: ${arrayToSort}`); |
26 | 26 |
|
27 | | - for (var j = i + 1; j < length; j++) { |
28 | | - console.log(`comparing ${arrayToSort[i]} against ${arrayToSort[j]} at position ${j}`); |
29 | | - checkIfSwap(arrayToSort, i, j); |
| 27 | + for (var j = i + 1; j < length; j++) { |
| 28 | + console.log(`comparing ${arrayToSort[i]} against ${arrayToSort[j]} at position ${j}`); |
| 29 | + this.checkIfSwap(arrayToSort, i, j); |
| 30 | + } |
| 31 | + |
| 32 | + console.log(`new order: ${arrayToSort}`); |
30 | 33 | } |
31 | 34 |
|
32 | | - console.log(`new order: ${arrayToSort}`); |
| 35 | + return arrayToSort; |
33 | 36 | } |
| 37 | +} |
34 | 38 |
|
35 | | - return arrayToSort; |
36 | | -}; |
37 | | - |
38 | | -console.log(`original array: ${theArray}`); |
39 | | -const sortedArray = bubbleSort(theArray); |
40 | | -console.log(`sorted array: ${sortedArray}`); |
0 commit comments