Skip to content

Commit 7668a1f

Browse files
authored
More efficient bubble sort (#141)
1 parent fd48226 commit 7668a1f

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

array/bubble_sort.go

+7-4
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@ package array
22

33
// BubbleSort solves the problem in O(n^2) time and O(1) space.
44
func BubbleSort(input []int) {
5-
for i := range input {
6-
for j := range input {
7-
if input[i] < input[j] {
8-
input[i], input[j] = input[j], input[i]
5+
swapped := true
6+
for swapped {
7+
swapped = false
8+
for i := 1; i < len(input); i++ {
9+
if input[i] < input[i-1] {
10+
input[i], input[i-1] = input[i-1], input[i]
11+
swapped = true
912
}
1013
}
1114
}

0 commit comments

Comments
 (0)