|
| 1 | +// sample of arrays to sort |
| 2 | +const arrayRandom = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8]; |
| 3 | +const arrayOrdered = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
| 4 | +const arrayReversed = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]; |
| 5 | + |
| 6 | +// be careful: this is a very basic implementation which is nice to understand the deep principle of bubble sort (going through all comparisons) but it can be greatly improved for performances |
| 7 | +function bubbleSortBasic(array) { |
| 8 | + let countOuter = 0; |
| 9 | + let countInner = 0; |
| 10 | + let countSwap = 0; |
| 11 | + |
| 12 | + for(let i = 0; i < array.length; i++) { |
| 13 | + countOuter++; |
| 14 | + for(let j = 1; j < array.length; j++) { |
| 15 | + countInner++; |
| 16 | + if(array[j - 1] > array[j]) { |
| 17 | + countSwap++; |
| 18 | + [array[j - 1], array[j]] = [array[j], array[j - 1]]; |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap); |
| 24 | + return array; |
| 25 | +} |
| 26 | + |
| 27 | +bubbleSortBasic(arrayRandom.slice()); // => outer: 10 inner: 90 swap: 21 |
| 28 | +bubbleSortBasic(arrayOrdered.slice()); // => outer: 10 inner: 90 swap: 0 |
| 29 | +bubbleSortBasic(arrayReversed.slice()); // => outer: 10 inner: 90 swap: 45 |
| 30 | + |
| 31 | +// correct implementation: this is the usual implementation of the bubble sort algorithm. Some loops execution are avoided if not they are not needed |
| 32 | +function bubbleSort(array) { |
| 33 | + let countOuter = 0; |
| 34 | + let countInner = 0; |
| 35 | + let countSwap = 0; |
| 36 | + |
| 37 | + let swapped; |
| 38 | + do { |
| 39 | + countOuter++; |
| 40 | + swapped = false; |
| 41 | + for(let i = 0; i < array.length; i++) { |
| 42 | + countInner++; |
| 43 | + if(array[i] && array[i + 1] && array[i] > array[i + 1]) { |
| 44 | + countSwap++; |
| 45 | + [array[i], array[i + 1]] = [array[i + 1], array[i]]; |
| 46 | + swapped = true; |
| 47 | + } |
| 48 | + } |
| 49 | + } while(swapped); |
| 50 | + |
| 51 | + console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap); |
| 52 | + return array; |
| 53 | +} |
| 54 | + |
| 55 | +bubbleSort(arrayRandom.slice()); // => outer: 9 inner: 90 swap: 21 |
| 56 | +bubbleSort(arrayOrdered.slice()); // => outer: 1 inner: 10 swap: 0 |
| 57 | +bubbleSort(arrayReversed.slice()); // => outer: 10 inner: 100 swap: 45 |
0 commit comments