Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit dbc98d0

Browse files
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
1 parent 041918d commit dbc98d0

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

‎Sorts/BubbleSort.js

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* compares adjacent element and swaps their position
33
* The big O on bubble sort in worst and best case is O(N^2).
44
* Not efficient.
5+
* Somehow if the array is sorted or nearly sorted then we can optimize bubble sort by adding a flag.
56
*
67
* In bubble sort, we keep iterating while something was swapped in
78
* the previous inner-loop iteration. By swapped I mean, in the
@@ -17,16 +18,23 @@
1718
*/
1819
export function bubbleSort (items) {
1920
const length = items.length
21+
let noSwaps
2022

21-
for (let i = (length - 1); i > 0; i--) {
23+
for (let i = length; i > 0; i--) {
24+
// flag for optimization
25+
noSwaps = true
2226
// Number of passes
23-
for (let j = (length - i); j>0;j--) {
27+
for (let j = 0;j<(i - 1); j++) {
2428
// Compare the adjacent positions
25-
if (items[j] < items[j - 1]) {
29+
if (items[j] > items[j + 1]) {
2630
// Swap the numbers
27-
[items[j], items[j - 1]] = [items[j - 1], items[j]]
31+
[items[j], items[j + 1]] = [items[j + 1], items[j]]
32+
noSwaps = false
2833
}
2934
}
35+
if (noSwaps) {
36+
break
37+
}
3038
}
3139

3240
return items

‎Sorts/test/BubbleSort.test.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ describe('bubbleSort', () => {
66
expect(bubbleSort([])).toEqual([])
77
expect(bubbleSort([1, 2, 3])).toEqual([1, 2, 3])
88
expect(bubbleSort([5, 6, 7, 8, 1, 2, 12, 14])).toEqual([1, 2, 5, 6, 7, 8, 12, 14])
9+
expect(bubbleSort([5, 6, 7, 8, 9, 4])).toEqual([4, 5, 6, 7, 8, 9])
910
})
1011
})
1112

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /