Série: Go
go
83 linhas
· Atualizado 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)
}
}
Artigos relacionados
Go
go
Atualizado 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/hashpw/main.go).
Ler artigo →
Go
go
Atualizado 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/server/main.go).
Ler artigo →
Go
go
Atualizado 2026-04-18
docs.go
docs.go — go source code from the Go learning materials (Go/Baasid/docs/docs.go).
Ler artigo →
Go
go
Atualizado 2026-04-18
jwt.go
jwt.go — go source code from the Go learning materials (Go/Baasid/internal/auth/jwt.go).
Ler artigo →
Go
go
Atualizado 2026-04-18
password.go
password.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password.go).
Ler artigo →
Go
go
Atualizado 2026-04-18
password_test.go
password_test.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password_test.go).
Ler artigo →