63 lines
1.1 KiB
Go
63 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func main() {
|
|
inBytes, err := os.ReadFile(os.Args[1])
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
inLines := strings.Split(strings.TrimSpace(string(inBytes)), "\n")
|
|
inInts := make([]int64, len(inLines))
|
|
|
|
for i, line := range inLines {
|
|
v, err := strconv.ParseInt(line, 0, 64)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
inInts[i] = v
|
|
}
|
|
|
|
if err := insertionSort(inInts); err != nil {
|
|
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
for _, i := range inInts {
|
|
fmt.Printf("%v\n", i)
|
|
}
|
|
}
|
|
|
|
func insertionSort(inInts []int64) error {
|
|
if len(inInts) < 2 {
|
|
return nil
|
|
}
|
|
|
|
for j := 1; j < len(inInts); j += 1 {
|
|
key := inInts[j]
|
|
fmt.Fprintf(os.Stderr, "%+v (save %v from %v)\n", inInts, key, j)
|
|
|
|
i := j - 1
|
|
|
|
for ; i > -1 && inInts[i] > key; i -= 1 {
|
|
inInts[i+1] = inInts[i]
|
|
|
|
fmt.Fprintf(os.Stderr, "%+v (j=%v i=%v)\n", inInts, j, i)
|
|
}
|
|
|
|
inInts[i+1] = key
|
|
fmt.Fprintf(os.Stderr, "%+v (insert %v at %v)\n", inInts, key, i+1)
|
|
}
|
|
|
|
return nil
|
|
}
|