Created
May 10, 2021 20:41
-
-
Save kiambogo/33bbbb2ee208a1190429534858b6ae0f to your computer and use it in GitHub Desktop.
Go BubbleSort
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 main | |
import ( | |
"log" | |
) | |
func main() { | |
array := []int{} | |
bubbleSort(&array) | |
assert([]int{}, array) | |
array = []int{1} | |
bubbleSort(&array) | |
assert([]int{1}, array) | |
array = []int{1, 2} | |
bubbleSort(&array) | |
assert([]int{1, 2}, array) | |
array = []int{3, 1, 2} | |
bubbleSort(&array) | |
assert([]int{1, 2, 3}, array) | |
array = []int{3, 2, 1, 4} | |
bubbleSort(&array) | |
assert([]int{1, 2, 3, 4}, array) | |
} | |
func bubbleSort(arr *[]int) { | |
if len(*arr) <= 1 { | |
return | |
} | |
arrPtr := *arr | |
swapped := true | |
for swapped { | |
swapped = false | |
for i := range arrPtr[:len(arrPtr)-1] { | |
if arrPtr[i] > arrPtr[i+1] { | |
tmp := arrPtr[i] | |
arrPtr[i] = arrPtr[i+1] | |
arrPtr[i+1] = tmp | |
swapped = true | |
} | |
} | |
} | |
return | |
} | |
func assert(expected, actual []int) { | |
if len(expected) != len(actual) { | |
log.Panicf("%s != %s", expected, actual) | |
} | |
for x := range expected { | |
if expected[x] != actual[x] { | |
log.Panicf("%s != %s", expected, actual) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment