|
| 1 | +// Overview |
| 2 | +// Bubblesort is an inefficient sorting algorithm that is simple to understand and therefore often taught in introductory computer science courses as an example how not to sort a list. Nevertheless, it is correct in the sense that it eventually produces a sorted version of the original list when executed to completion. |
| 3 | + |
| 4 | +// At the heart of Bubblesort is what is known as a pass. Let's look at an example at how a pass works. |
| 5 | + |
| 6 | +// Consider the following list: |
| 7 | + |
| 8 | +// 9, 7, 5, 3, 1, 2, 4, 6, 8 |
| 9 | +// We initiate a pass by comparing the first two elements of the list. Is the first element greater than the second? If so, we swap the two elements. Since 9 is greater than 7 in this case, we swap them to give 7, 9. The list then becomes: |
| 10 | + |
| 11 | +// 7, 9, 5, 3, 1, 2, 4, 6, 8 |
| 12 | +// We then continue the process for the 2nd and 3rd elements, 3rd and 4th elements ... all the way up to the last two elements. When the pass is complete, our list becomes: |
| 13 | + |
| 14 | +// 7, 5, 3, 1, 2, 4, 6, 8, 9 |
| 15 | + |
| 16 | + |
| 17 | +function bubblesortOnce(a) { |
| 18 | + |
| 19 | + let newArr = [...a] |
| 20 | + for(let i = 0; i < 1; i++){ |
| 21 | + for(let j = 0; j < newArr.length; j++){ |
| 22 | + if(newArr[j] > newArr[j + 1]){ |
| 23 | + let temp = newArr[j]; |
| 24 | + newArr[j] = newArr[j + 1] |
| 25 | + newArr[j + 1] = temp |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + return newArr |
| 30 | +} |
| 31 | + |
| 32 | +// Refactor |
| 33 | + |
| 34 | +function bubblesortOnce(a) { |
| 35 | + return [...a].map((e, i, arr) => e > arr[i+1] ? (arr[i] = arr[i+1], arr[i+1] = e, arr[i]) : e) |
| 36 | + |
| 37 | +} |
| 38 | + |
| 39 | +//Another approach |
| 40 | + |
| 41 | +function bubblesortOnce(arr) { |
| 42 | + let newArr = arr.slice(); |
| 43 | + for (let i = 0; i < newArr.length - 1; i++) { |
| 44 | + if (newArr[i] > newArr[i + 1]) { |
| 45 | + [newArr[i], newArr[i + 1]] = [newArr[i + 1], newArr[i]]; |
| 46 | + } |
| 47 | + } |
| 48 | + return newArr; |
| 49 | +} |
0 commit comments