From e5166ee912969e64003fc0f60b7cc57d3927db06 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 27 Apr 2024 22:22:56 -0400 Subject: [PATCH] Sorting negative cards --- intro-to-algorithms/insertion_sort.go | 62 +++++++++++++++++++++++++++ intro-to-algorithms/ints00 | 10 +++++ 2 files changed, 72 insertions(+) create mode 100644 intro-to-algorithms/insertion_sort.go create mode 100644 intro-to-algorithms/ints00 diff --git a/intro-to-algorithms/insertion_sort.go b/intro-to-algorithms/insertion_sort.go new file mode 100644 index 0000000..6a55f84 --- /dev/null +++ b/intro-to-algorithms/insertion_sort.go @@ -0,0 +1,62 @@ +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 +} diff --git a/intro-to-algorithms/ints00 b/intro-to-algorithms/ints00 new file mode 100644 index 0000000..651d427 --- /dev/null +++ b/intro-to-algorithms/ints00 @@ -0,0 +1,10 @@ +11 +2 +17 +-1 +34 +8 +999 +2 +-56 +3