Stuntkoala

Go Insertion Sort

Dec 6th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.71 KB | None | 0 0
  1. package main
  2.  
  3. import ("fmt"
  4.         "math/rand"
  5.         "time")
  6.  
  7. const ARLEN int = 10
  8.  
  9. func randomArray() [ARLEN]int {
  10.     seed := rand.NewSource(time.Now().UnixNano())
  11.     rnd := rand.New(seed)
  12.     var arr [ARLEN]int
  13.     for i:=0; i<ARLEN; i++ {
  14.         arr[i] = rnd.Intn(100)
  15.     }
  16.     return arr
  17. }
  18.  
  19. func swap(arr *[ARLEN]int, a, b int) {
  20.     temp := arr[a]
  21.     arr[a] = arr[b]
  22.     arr[b] = temp
  23. }
  24.  
  25. func insertionSort(arr *[ARLEN]int) {
  26.     for i:=1; i<ARLEN; i++ {
  27.         toSort := arr[i]
  28.         k:=i
  29.         for ;k>0 && arr[k-1] > toSort ; k--{
  30.             swap(arr, k, k-1)
  31.         }
  32.         arr[k] = toSort
  33.     }
  34. }
  35.  
  36. func main() {
  37.     arr := randomArray()
  38.     fmt.Println("generated random Array:", arr)
  39.  
  40.     insertionSort(&arr)
  41.     fmt.Println("Insertionsorted Array:", arr)
  42. }
Advertisement
Add Comment
Please, Sign In to add comment