bubblesort.go 615 B

123456789101112131415161718192021222324252627
  1. // Q14_Bubblesort.go
  2. package main
  3. import (
  4. "fmt"
  5. )
  6. func main() {
  7. sla := []int{2, 6, 4, -10, 8, 89, 12, 68, -45, 37}
  8. fmt.Println("before sort: ", sla)
  9. // sla is passed via call by value, but since sla is a reference type
  10. // the underlying slice is array is changed (sorted)
  11. bubbleSort(sla)
  12. fmt.Println("after sort: ", sla)
  13. }
  14. func bubbleSort(sl []int) {
  15. // passes through the slice:
  16. for pass := 1; pass < len(sl); pass++ {
  17. // one pass:
  18. for i := 0; i < len(sl)-pass; i++ { // the bigger value 'bubbles up' to the last position
  19. if sl[i] > sl[i+1] {
  20. sl[i], sl[i+1] = sl[i+1], sl[i]
  21. }
  22. }
  23. }
  24. }