|
| 1 | +# 0008 BubbleSort ( L-I ) |
| 2 | + |
| 3 | +## Problem |
| 4 | + |
| 5 | +Implement a function that sorts an array in increasing order using bubble sort. |
| 6 | + |
| 7 | +## Testcases |
| 8 | + |
| 9 | +- Input: `[0, 4, 2, 3, 7, 3, 6, 2, 9, 10, 2, 6]` <br> |
| 10 | + Output: `[0, 2, 2, 2, 3, 3, 4, 6, 6, 7, 9, 10]` |
| 11 | + |
| 12 | +- Input: `[45, 32, 12, 67, 86, 92, 29, 24, 53, 1, 6, 32, 56]` <br> |
| 13 | + Output: `[1, 6, 12, 24, 29, 32, 32, 45, 53, 56, 67, 86, 92]` |
| 14 | + |
| 15 | +## Solution |
| 16 | + |
| 17 | +```javascript |
| 18 | +const BubbleSort = (arr) => { |
| 19 | + for (let i = 0; i < arr.length - 1; i++) { |
| 20 | + for (let j = 0; j < arr.length - i - 1; j++) { |
| 21 | + if (arr[j] > arr[j + 1]) { |
| 22 | + temp = arr[j]; |
| 23 | + arr[j] = arr[j + 1]; |
| 24 | + arr[j + 1] = temp; |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | +}; |
| 29 | +``` |
| 30 | + |
| 31 | +## How it works |
| 32 | + |
| 33 | +- The function takes an array of integers `arr` as an argument. |
| 34 | +- The function runs a for loop in `i` until the second last element. This is due to the fact that on every iteration of the `i` loop, the last `i` elements are sorted. Therefore, running the `i` loop for the first element is unnecessary. |
| 35 | +- The inner loop runs in `j` and will traverse `arr` from the start to the `n - i`th position since the last `i` elements are sorted. |
| 36 | +- The function terminates with the sorted `arr`. |
| 37 | +- The function will also work for those arrays that have duplicate elements. |
| 38 | + |
| 39 | +## References |
| 40 | + |
| 41 | +- [GeeksForGeeks](https://www.geeksforgeeks.org/bubble-sort/) |
| 42 | + |
| 43 | +## Problem Added By |
| 44 | + |
| 45 | +- [GitHub](https://www.github.com/khairalanam) |
| 46 | +- [LinkedIn](https://www.linkedin.com/in/khair-alanam-b27b69221/) |
| 47 | +- [Twitter](https://twitter.com/khair_alanam) |
| 48 | + |
| 49 | +## Contributing |
| 50 | + |
| 51 | +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. |
0 commit comments