Skip to content

Instantly share code, notes, and snippets.

@jasonsalas
Created January 9, 2022 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonsalas/3c16db2bab5e7c2c556ed5f536a1b7b6 to your computer and use it in GitHub Desktop.
Save jasonsalas/3c16db2bab5e7c2c556ed5f536a1b7b6 to your computer and use it in GitHub Desktop.
Performance-testing loop types in bubble sort algorithm in Go (for/each vs. while vs. infinite loops)
// simple sorting algorithms
package main
import "fmt"
func getNumbers() []int {
return []int{12, 7, 256, 4, 22, 44, 55, 85, 56, 3, 6, 1, 98, 76}
}
func RangeLoopSort(arr []int) []int {
for i := range arr {
for j := range arr {
if arr[i] < arr[j] {
arr[i], arr[j] = arr[j], arr[i]
}
}
}
return arr
}
func ForEachLoopSort(arr []int) []int {
for i := 1; i < len(arr); i++ {
for j := 0; j < len(arr)-1; j++ {
if arr[i] < arr[j] {
arr[i], arr[j] = arr[j], arr[i]
}
}
}
return arr
}
func InfiniteLoopSort(arr []int) []int {
var isSwapped bool
isSwapped = true
for isSwapped {
isSwapped = false
var i int
for i = 1; i < len(arr); i++ {
if arr[i-1] > arr[i] {
var temp = arr[i]
arr[i] = arr[i-1]
arr[i-1] = temp
isSwapped = true
}
}
}
return arr
}
func main() {
arr := getNumbers()
fmt.Printf("infinite loop: %v\n", ForEachLoopSort(arr))
fmt.Printf("range loop: %v\n", RangeLoopSort(arr))
fmt.Printf("for/each loop: %v\n", InfiniteLoopSort(arr))
}
package main
import "testing"
func BenchmarkRangeSort(b *testing.B) {
// run the bubble sort algorithm b.N times
for n := 0; n < b.N; n++ {
RangeLoopSort(getNumbers())
}
}
func BenchmarkForEachLoopSort(b *testing.B) {
// run the bubble sort algorithm b.N times
for n := 0; n < b.N; n++ {
ForEachLoopSort(getNumbers())
}
}
func BenchmarkInfiniteLoopSort(b *testing.B) {
// run the swap sort algorithm b.N times
for n := 0; n < b.N; n++ {
InfiniteLoopSort(getNumbers())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment