let me know what I can improve in this code.
For a real-world code review, code should be correct, maintainable, reasonably efficient, and, most importantly, readable.
Writing code is a process of stepwise refinement.
Here's your code. Consider it as a first draft.
func BubbleSort(arr []int) []int {
keepRunning := true
for keepRunning {
keepRunning = false
for i := 0; i < len(arr)-1; i++ {
a := arr[i]
b := arr[i+1]
if a > b {
arr[i], arr[i+1] = b, a
keepRunning = true
}
}
}
return arr
}
Simplify the code. Express the do ... until construct directly. Remove unnecessary variables. Remove the redundant return value. And so on.
func BubbleSort(a []int) {
for {
swap := false
for i := 1; i < len(a); i++ {
if a[i-1] > a[i] {
a[i-1], a[i] = a[i], a[i-1]
swap = true
}
}
if !swap {
return
}
}
}
Optimize the code. Each pass sorts at least one element to the top.
func BubbleSort(a []int) {
for i := len(a); i > 0; i-- {
swap := false
for j := 1; j < i; j++ {
if a[j-1] > a[j] {
a[j-1], a[j] = a[j], a[j-1]
swap = true
}
}
if !swap {
return
}
}
}
Seek further optimizations. Elements from and above the last swap are sorted.
func BubbleSort(a []int) {
for i := len(a); i > 1; {
swap := 0
for j := 1; j < i; j++ {
if a[j-1] > a[j] {
a[j-1], a[j] = a[j], a[j-1]
swap = j
}
}
i = swap
}
}
Playground: https://play.golang.org/p/jpoUO5nsJEo
Output:
[7 5 6 9 8]
[5 6 7 8 9]
Write tests using the Go testing package.
Run benchmarks using the Go testing package.
Comment: I was wondering if I could remove the keepRunning bool
somehow. and in the above case the swap variable – STEEL
The swap state variable is used to end the sort as soon as possible. It is not necessary.
For example,
func BubbleSort(a []int) {
for i := 1; i < len(a); i++ {
for j := len(a) - 1; j >= i; j-- {
if a[j-1] > a[j] {
a[j-1], a[j] = a[j], a[j-1]
}
}
}
}
sort.Slice(elements, func(a, b int) bool { return a < b })
does not work because yourless
function is wrong. See sort func Slice:func Slice(slice interface{}, less func(i, j int) bool)
. For example, play.golang.org/p/uP5_XZHWqb8. \$\endgroup\$