I'm new to Go. I'm using go version go1.10.4 linux/amd64
. My objective is to ask a single integer input from the user append it to an array and sort it. I'm using insertion sort for this. The program needs to exit on receiving 'X'
as input from the user.
This is my code:
package main
import (
"fmt"
"strconv"
// "sort"
)
func insertionSort(arr []int) []int {
// Traverse through 1 to len(arr)
for i, _ := range arr[1:] {
key := arr[i]
j := i - 1
for {
if j >= 0 && key < arr[j] {
arr[j+1] = arr[j]
j = j - 1
} else {
break
}
}
arr[j+1] = key
}
return arr
}
func main() {
s := make([]int, 0, 3)
var x string
for {
fmt.Printf("Enter a number: ")
fmt.Scan(&x)
if x == "X" {
break
}
xInt, _ := strconv.Atoi(x)
fmt.Println(xInt)
s = append(s, xInt)
//sort.Ints(s)
s = insertionSort(s)
fmt.Printf("%v
", s)
}
fmt.Printf("%v
", s)
}
I'm getting the following output:
Enter a number: 5
[5]
Enter a number: 4
[5 4]
Enter a number: 3
[4 5 3]
Enter a number: 2
[3 4 5 2]
Enter a number: 1
[2 3 4 5 1]
Enter a number: X
[2 3 4 5 1]
Question:
Why is it getting sorted in 2nd pass? I mean it's first printing the appended array and then for next element, it's printing the sorted array of the previous element. Why? I'm sorting after appending so this should not be the case...
I took (and converted from Python
code) insertion sort code from here