mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 17:50:39 +08:00
merge: Bubble Sort enhancements for nearly sorted or sorted array, added test cases and documentation (#895)
* BubbleSort enacements for nearly sorted or sorted array and added test cases * BubbleSort enacements for nearly sorted or sorted array and added test cases * Bubble sort requested changes solved * standard js style issue fixed
This commit is contained in:
@ -2,6 +2,7 @@
|
|||||||
* compares adjacent element and swaps their position
|
* compares adjacent element and swaps their position
|
||||||
* The big O on bubble sort in worst and best case is O(N^2).
|
* The big O on bubble sort in worst and best case is O(N^2).
|
||||||
* Not efficient.
|
* Not efficient.
|
||||||
|
* Somehow if the array is sorted or nearly sorted then we can optimize bubble sort by adding a flag.
|
||||||
*
|
*
|
||||||
* In bubble sort, we keep iterating while something was swapped in
|
* In bubble sort, we keep iterating while something was swapped in
|
||||||
* the previous inner-loop iteration. By swapped I mean, in the
|
* the previous inner-loop iteration. By swapped I mean, in the
|
||||||
@ -17,16 +18,23 @@
|
|||||||
*/
|
*/
|
||||||
export function bubbleSort (items) {
|
export function bubbleSort (items) {
|
||||||
const length = items.length
|
const length = items.length
|
||||||
|
let noSwaps
|
||||||
|
|
||||||
for (let i = (length - 1); i > 0; i--) {
|
for (let i = length; i > 0; i--) {
|
||||||
|
// flag for optimization
|
||||||
|
noSwaps = true
|
||||||
// Number of passes
|
// Number of passes
|
||||||
for (let j = (length - i); j > 0; j--) {
|
for (let j = 0; j < (i - 1); j++) {
|
||||||
// Compare the adjacent positions
|
// Compare the adjacent positions
|
||||||
if (items[j] < items[j - 1]) {
|
if (items[j] > items[j + 1]) {
|
||||||
// Swap the numbers
|
// Swap the numbers
|
||||||
[items[j], items[j - 1]] = [items[j - 1], items[j]]
|
[items[j], items[j + 1]] = [items[j + 1], items[j]]
|
||||||
|
noSwaps = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (noSwaps) {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return items
|
return items
|
||||||
|
@ -6,6 +6,7 @@ describe('bubbleSort', () => {
|
|||||||
expect(bubbleSort([])).toEqual([])
|
expect(bubbleSort([])).toEqual([])
|
||||||
expect(bubbleSort([1, 2, 3])).toEqual([1, 2, 3])
|
expect(bubbleSort([1, 2, 3])).toEqual([1, 2, 3])
|
||||||
expect(bubbleSort([5, 6, 7, 8, 1, 2, 12, 14])).toEqual([1, 2, 5, 6, 7, 8, 12, 14])
|
expect(bubbleSort([5, 6, 7, 8, 1, 2, 12, 14])).toEqual([1, 2, 5, 6, 7, 8, 12, 14])
|
||||||
|
expect(bubbleSort([5, 6, 7, 8, 9, 4])).toEqual([4, 5, 6, 7, 8, 9])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user