S SmartDocs
Series: Go go 83 lines · Updated 2026-04-18

sorts_test.go

Go/part2-dsa/ds/sortx/sorts_test.go

package sortx

import (
	"math/rand"
	"reflect"
	"sort"
	"testing"
)

func cloneInts(s []int) []int {
	c := make([]int, len(s))
	copy(c, s)
	return c
}

func TestSortsInt(t *testing.T) {
	cases := [][]int{
		{},
		{1},
		{2, 1},
		{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5},
		{5, 5, 5, 5, 5},
		{1, 2, 3, 4, 5},
		{5, 4, 3, 2, 1},
	}
	for _, in := range cases {
		want := cloneInts(in)
		sort.Ints(want)

		for name, fn := range map[string]func([]int){
			"Bubble":    BubbleSort[int],
			"Insertion": InsertionSort[int],
			"Quick":     QuickSort[int],
			"Heap":      HeapSort[int],
		} {
			got := cloneInts(in)
			fn(got)
			if !reflect.DeepEqual(got, want) {
				t.Errorf("%s(%v) = %v, want %v", name, in, got, want)
			}
		}

		mg := MergeSort(in)
		if !reflect.DeepEqual(mg, want) {
			t.Errorf("MergeSort(%v) = %v, want %v", in, mg, want)
		}
	}
}

func TestRandomInts(t *testing.T) {
	r := rand.New(rand.NewSource(42))
	in := make([]int, 1000)
	for i := range in {
		in[i] = r.Intn(10000)
	}
	want := cloneInts(in)
	sort.Ints(want)

	for name, fn := range map[string]func([]int){
		"Quick": QuickSort[int],
		"Heap":  HeapSort[int],
	} {
		got := cloneInts(in)
		fn(got)
		if !reflect.DeepEqual(got, want) {
			t.Errorf("%s mismatch", name)
		}
	}
	if !reflect.DeepEqual(MergeSort(in), want) {
		t.Errorf("MergeSort mismatch")
	}
}

func TestSortStrings(t *testing.T) {
	in := []string{"pear", "apple", "banana", "cherry"}
	want := []string{"apple", "banana", "cherry", "pear"}

	got := append([]string(nil), in...)
	HeapSort(got)
	if !reflect.DeepEqual(got, want) {
		t.Errorf("HeapSort strings = %v", got)
	}
}

Related articles