Last active
July 24, 2023 16:53
-
-
Save maxclav/6e029b6beb6d6b6e9b6bf4bb31c6d7a5 to your computer and use it in GitHub Desktop.
Simple and custom bubble sort in Go (GoLang).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package slice | |
// For learning purpose only. | |
// Please, use the sort package of Go's Standard library: https://pkg.go.dev/sort | |
// BubbleSort sorts the slice `vals` with the | |
// bubble sort algorithm. | |
// Time: O(n^2) | |
// Space: O(1) | |
func BubbleSort(vals []int) { | |
// Time: O(n) | |
for i := 1; i < len(vals); i++ { | |
// Time: O(n) | |
for j := 1; j < len(vals)-i+1; j++ { | |
if vals[j-1] > vals[j] { | |
vals[j-1], vals[j] = vals[j], vals[j-1] | |
} | |
} | |
} | |
} | |
/* | |
As you can see with the previous answer, we started with i=1 and j=1 . | |
We can also start with i=0 and j=0: | |
// BubbleSort sorts the slice `vals` with the | |
// bubble sort algorithm. | |
// Time: O(n^2) | |
// Space: O(1) | |
func BubbleSort(vals []int) { | |
// Time: O(n) | |
for i := 0; i < len(vals)-1; i++ { | |
// Time: O(n) | |
for j := 0; j < len(vals)-i-1; j++ { | |
if vals[j] > vals[j+1] { | |
vals[j], vals[j+1] = vals[j+1], vals[j] | |
} | |
} | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment