2020-10-09 22:58:41 +05:30
|
|
|
/* Bubble Sort is an algorithm to sort an array. It
|
2021-09-04 00:18:49 -07:00
|
|
|
* compares adjacent element and swaps their position
|
2020-10-09 22:58:41 +05:30
|
|
|
* The big O on bubble sort in worst and best case is O(N^2).
|
|
|
|
|
* Not efficient.
|
2022-02-19 18:23:54 +06:00
|
|
|
* Somehow if the array is sorted or nearly sorted then we can optimize bubble sort by adding a flag.
|
2020-10-09 22:58:41 +05:30
|
|
|
*
|
|
|
|
|
* In bubble sort, we keep iterating while something was swapped in
|
|
|
|
|
* the previous inner-loop iteration. By swapped I mean, in the
|
|
|
|
|
* inner loop iteration, we check each number if the number proceeding
|
|
|
|
|
* it is greater than itself, if so we swap them.
|
|
|
|
|
*
|
|
|
|
|
* Wikipedia: https://en.wikipedia.org/wiki/Bubble_sort
|
2021-01-24 23:29:50 +05:30
|
|
|
* Animated Visual: https://www.toptal.com/developers/sorting-algorithms/bubble-sort
|
2017-08-11 13:41:48 +05:30
|
|
|
*/
|
2020-05-04 11:58:44 +05:30
|
|
|
|
2021-10-07 09:03:38 +02:00
|
|
|
/**
|
|
|
|
|
* Using 2 for loops.
|
|
|
|
|
*/
|
|
|
|
|
export function bubbleSort (items) {
|
2020-05-04 11:58:44 +05:30
|
|
|
const length = items.length
|
2022-02-19 18:23:54 +06:00
|
|
|
let noSwaps
|
2020-10-09 22:58:41 +05:30
|
|
|
|
2022-02-19 18:23:54 +06:00
|
|
|
for (let i = length; i > 0; i--) {
|
|
|
|
|
// flag for optimization
|
|
|
|
|
noSwaps = true
|
2020-05-04 11:58:44 +05:30
|
|
|
// Number of passes
|
2022-02-19 18:23:54 +06:00
|
|
|
for (let j = 0; j < (i - 1); j++) {
|
2020-05-04 11:58:44 +05:30
|
|
|
// Compare the adjacent positions
|
2022-02-19 18:23:54 +06:00
|
|
|
if (items[j] > items[j + 1]) {
|
2020-05-04 11:58:44 +05:30
|
|
|
// Swap the numbers
|
2022-02-19 18:23:54 +06:00
|
|
|
[items[j], items[j + 1]] = [items[j + 1], items[j]]
|
|
|
|
|
noSwaps = false
|
2020-05-04 11:58:44 +05:30
|
|
|
}
|
2017-08-11 13:41:48 +05:30
|
|
|
}
|
2022-02-19 18:23:54 +06:00
|
|
|
if (noSwaps) {
|
|
|
|
|
break
|
|
|
|
|
}
|
2020-05-04 11:58:44 +05:30
|
|
|
}
|
2017-08-11 13:41:48 +05:30
|
|
|
|
2020-10-09 22:58:41 +05:30
|
|
|
return items
|
|
|
|
|
}
|
2017-10-16 11:23:46 +01:00
|
|
|
|
2021-10-07 09:03:38 +02:00
|
|
|
/**
|
|
|
|
|
* Using a while loop and a for loop.
|
|
|
|
|
*/
|
|
|
|
|
export function alternativeBubbleSort (arr) {
|
2020-05-04 11:58:44 +05:30
|
|
|
let swapped = true
|
2020-10-09 22:58:41 +05:30
|
|
|
|
2020-05-04 11:58:44 +05:30
|
|
|
while (swapped) {
|
|
|
|
|
swapped = false
|
|
|
|
|
for (let i = 0; i < arr.length - 1; i++) {
|
|
|
|
|
if (arr[i] > arr[i + 1]) {
|
2020-05-23 14:01:41 +08:00
|
|
|
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]
|
2020-05-04 11:58:44 +05:30
|
|
|
swapped = true
|
|
|
|
|
}
|
2017-10-16 12:56:02 +01:00
|
|
|
}
|
2020-05-04 11:58:44 +05:30
|
|
|
}
|
2020-10-09 22:58:41 +05:30
|
|
|
|
2020-05-04 11:58:44 +05:30
|
|
|
return arr
|
2017-10-16 12:56:02 +01:00
|
|
|
}
|