summaryrefslogtreecommitdiff
path: root/sort/sort_test.go
blob: bd9db9b706a3ebaed9dd04211928eabaee85f5d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package sort

import (
	"algorithms/ds"
	"fmt"
	"testing"
)

// Store results here to avoid compiler optimizations
var benchResult ds.ArrayList
var benchResultInt []int

const maxLength int = 10000

type sortAlgorithm func(ds.ArrayList) ds.ArrayList
type sortAlgorithmInt func([]int) []int

func TestSelectionSort(t *testing.T) {
	for i := 1; i <= maxLength; i *= 10 {
		test(Selection, i, t)
	}
}

func TestInsertionSort(t *testing.T) {
	for i := 1; i <= maxLength; i *= 10 {
		test(Insertion, i, t)
	}
}

func TestShellSort(t *testing.T) {
	for i := 1; i <= maxLength; i *= 10 {
		test(Shell, i, t)
	}
}

func TestQuickSort(t *testing.T) {
	for i := 1; i <= maxLength; i *= 10 {
		test(Quick, i, t)
	}
}

func TestShuffleSort(t *testing.T) {
	for i := 10; i <= maxLength; i *= 10 {
		testShuffle(Shuffle, i, t)
	}
}

func BenchmarkInsertionSort(b *testing.B) {
	for i := 1; i <= maxLength; i *= 10 {
		benchmark(Insertion, i, b)
	}
}

func BenchmarkSelectionSort(b *testing.B) {
	for i := 1; i <= maxLength; i *= 10 {
		benchmark(Selection, i, b)
	}
}

func BenchmarkShellSort(b *testing.B) {
	for i := 1; i <= maxLength; i *= 10 {
		benchmark(Shell, i, b)
	}
}

func BenchmarkQuickSort(b *testing.B) {
	for i := 1; i <= maxLength; i *= 10 {
		benchmark(Quick, i, b)
	}
}

func BenchmarkShuffleSort(b *testing.B) {
	for i := 1; i <= maxLength; i *= 10 {
		benchmark(Shuffle, i, b)
	}
}

func test(sort sortAlgorithm, length int, t *testing.T) {
	cb := func(t *testing.T) {
		t.Parallel()
		a := makeIntegers(length, length)
		a = sort(a)
		if !a.Sorted() {
			t.Errorf("Array not sorted: %v", a)
		}
	}
	t.Run(fmt.Sprintf("%d", length), cb)
}

func testShuffle(sort sortAlgorithm, length int, t *testing.T) {
	cb := func(t *testing.T) {
		t.Parallel()
		a := sort(ds.SortedIntegers(length))
		if a.Sorted() {
			t.Errorf("Array sorted: %v", a.FirstN(10))
		}
	}
	t.Run(fmt.Sprintf("%d", length), cb)
}

func benchmark(sort sortAlgorithm, length int, b *testing.B) {
	cb := func(b *testing.B) {
		a := makeIntegers(length, length)
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			benchResult = sort(a)
		}
	}
	b.Run(fmt.Sprintf("%d", length), cb)
}

func makeIntegers(length, max int) ds.ArrayList {
	return ds.RandomIntegers(length, max)
}