package main
import (
"flag"
"fmt"
"sort"
"time"
"algo/metrics"
)
// cmdDC runs the divide-and-conquer sorts and reports counts and wall time.
func cmdDC(args []string) error {
fs := flag.NewFlagSet("dc", flag.ContinueOnError)
in := fs.String("in", "library.jsonl", "library file")
order := fs.String("order", "shuffled", "shuffled | sorted | reverse | nearly")
seed := fs.Int64("seed", 1, "seed for -order nearly")
if err := fs.Parse(args); err != nil {
return err
}
items, err := load(*in)
if err != nil {
return err
}
fmt.Printf("n = %d, order = %s\n\n", len(items), *order)
fmt.Printf("%-22s %16s %16s %12s\n", "algorithm", "comparisons", "moves", "wall")
run := func(name string, f func([]Item, *metrics.Counter, *metrics.Counter)) {
data := prepare(items, *order, *seed)
var cmp, mv metrics.Counter
start := time.Now()
f(data, &cmp, &mv)
el := time.Since(start)
ok := isSortedByTitle(data)
mark := ""
if !ok {
mark = " ** NOT SORTED **"
}
fmt.Printf("%-22s %16d %16d %12s%s\n", name, cmp.N(), mv.N(), el.Round(time.Microsecond), mark)
}
// Merge sort returns a new slice, so it gets its own wrapper.
{
data := prepare(items, *order, *seed)
var cmp, mv metrics.Counter
start := time.Now()
out := MergeSort(data, &cmp, &mv)
el := time.Since(start)
mark := ""
if !isSortedByTitle(out) {
mark = " ** NOT SORTED **"
}
fmt.Printf("%-22s %16d %16d %12s%s\n", "merge", cmp.N(), mv.N(), el.Round(time.Microsecond), mark)
}
run("quick (first pivot)", QuickSortNaive)
run("quick (median-of-3)", QuickSortMedian3)
run("quick (random)", QuickSortRandom)
return nil
}
// cmdStable is the smallest example that makes stability visible.
//
// Sort by Rating first, then by Artist. A STABLE sort by Artist leaves the
// ratings in order inside each artist; an unstable one scrambles them.
func cmdStable(args []string) error {
fs := flag.NewFlagSet("stable", flag.ContinueOnError)
n := fs.Int("n", 8, "how many rows to show")
if err := fs.Parse(args); err != nil {
return err
}
// A deliberately tiny library: two artists, four ratings each.
//
// Title carries the ARTIST here, because your MergeSort and QuickSort sort
// by Title — so this makes the second key the artist without needing a
// second set of sort functions.
mk := func(id int, artist string, rating int) Item {
return Item{ID: id, Artist: artist, Title: artist, Rating: rating}
}
base := []Item{
mk(1, "Nova", 10), mk(2, "Vega", 20), mk(3, "Nova", 30), mk(4, "Vega", 40),
mk(5, "Nova", 50), mk(6, "Vega", 60), mk(7, "Nova", 70), mk(8, "Vega", 80),
}
if *n < len(base) {
base = base[:*n]
}
byRating := func(items []Item) []Item {
out := append([]Item(nil), items...)
sort.SliceStable(out, func(i, j int) bool { return out[i].Rating < out[j].Rating })
return out
}
show := func(label string, items []Item) {
fmt.Printf("%-24s", label)
for _, it := range items {
fmt.Printf(" %s/%d", it.Artist[:1], it.Rating)
}
fmt.Println()
}
step1 := byRating(base)
show("1. sorted by rating:", step1)
// Now sort THAT by artist, two ways.
var c1, m1 metrics.Counter
stable := MergeSort(step1, &c1, &m1)
show("2a. then by artist (merge):", stable)
unstable := append([]Item(nil), step1...)
var c2, m2 metrics.Counter
QuickSortMedian3(unstable, &c2, &m2)
show("2b. then by artist (quick):", unstable)
fmt.Println()
fmt.Println("read the ratings inside each artist:")
fmt.Println(" merge keeps them ascending — the rating sort survived")
fmt.Println(" quick scrambles them — the rating sort was destroyed")
return nil
}