Debian Codegraph @

slices/sort_test.go

raw symbols SCIP
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package slices
6
7 import (
8 "cmp"
9 "fmt"
10 "math"
11 "math/rand"
12 "sort"
13 "strconv"
14 "strings"
15 "testing"
16 )
17
18 var ints = [...]int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}
19 var float64s = [...]float64{74.3, 59.0, math.Inf(1), 238.2, -784.0, 2.3, math.Inf(-1), 9845.768, -959.7485, 905, 7.8, 7.8, 74.3, 59.0, math.Inf(1), 238.2, -784.0, 2.3}
20 var float64sWithNaNs = [...]float64{74.3, 59.0, math.Inf(1), 238.2, -784.0, 2.3, math.NaN(), math.NaN(), math.Inf(-1), 9845.768, -959.7485, 905, 7.8, 7.8}
21 var strs = [...]string{"", "Hello", "foo", "bar", "foo", "f00", "%*&^*&^&", "***"}
22
23 func TestSortIntSlice(t *testing.T) {
24 data := Clone(ints[:])
25 Sort(data)
26 if !IsSorted(data) {
27 t.Errorf("sorted %v", ints)
28 t.Errorf(" got %v", data)
29 }
30 }
31
32 func TestSortFuncIntSlice(t *testing.T) {
33 data := Clone(ints[:])
34 SortFunc(data, func(a, b int) int { return a - b })
35 if !IsSorted(data) {
36 t.Errorf("sorted %v", ints)
37 t.Errorf(" got %v", data)
38 }
39 }
40
41 func TestSortFloat64Slice(t *testing.T) {
42 data := Clone(float64s[:])
43 Sort(data)
44 if !IsSorted(data) {
45 t.Errorf("sorted %v", float64s)
46 t.Errorf(" got %v", data)
47 }
48 }
49
50 func TestSortFloat64SliceWithNaNs(t *testing.T) {
51 data := float64sWithNaNs[:]
52 data2 := Clone(data)
53
54 Sort(data)
55 sort.Float64s(data2)
56
57 if !IsSorted(data) {
58 t.Error("IsSorted indicates data isn't sorted")
59 }
60
61 // Compare for equality using cmp.Compare, which considers NaNs equal.
62 if !EqualFunc(data, data2, func(a, b float64) bool { return cmp.Compare(a, b) == 0 }) {
63 t.Errorf("mismatch between Sort and sort.Float64: got %v, want %v", data, data2)
64 }
65 }
66
67 func TestSortStringSlice(t *testing.T) {
68 data := Clone(strs[:])
69 Sort(data)
70 if !IsSorted(data) {
71 t.Errorf("sorted %v", strs)
72 t.Errorf(" got %v", data)
73 }
74 }
75
76 func TestSortLarge_Random(t *testing.T) {
77 n := 1000000
78 if testing.Short() {
79 n /= 100
80 }
81 data := make([]int, n)
82 for i := 0; i < len(data); i++ {
83 data[i] = rand.Intn(100)
84 }
85 if IsSorted(data) {
86 t.Fatalf("terrible rand.rand")
87 }
88 Sort(data)
89 if !IsSorted(data) {
90 t.Errorf("sort didn't sort - 1M ints")
91 }
92 }
93
94 type intPair struct {
95 a, b int
96 }
97
98 type intPairs []intPair
99
100 // Pairs compare on a only.
101 func intPairCmp(x, y intPair) int {
102 return x.a - y.a
103 }
104
105 // Record initial order in B.
106 func (d intPairs) initB() {
107 for i := range d {
108 d[i].b = i
109 }
110 }
111
112 // InOrder checks if a-equal elements were not reordered.
113 func (d intPairs) inOrder() bool {
114 lastA, lastB := -1, 0
115 for i := 0; i < len(d); i++ {
116 if lastA != d[i].a {
117 lastA = d[i].a
118 lastB = d[i].b
119 continue
120 }
121 if d[i].b <= lastB {
122 return false
123 }
124 lastB = d[i].b
125 }
126 return true
127 }
128
129 func TestStability(t *testing.T) {
130 n, m := 100000, 1000
131 if testing.Short() {
132 n, m = 1000, 100
133 }
134 data := make(intPairs, n)
135
136 // random distribution
137 for i := 0; i < len(data); i++ {
138 data[i].a = rand.Intn(m)
139 }
140 if IsSortedFunc(data, intPairCmp) {
141 t.Fatalf("terrible rand.rand")
142 }
143 data.initB()
144 SortStableFunc(data, intPairCmp)
145 if !IsSortedFunc(data, intPairCmp) {
146 t.Errorf("Stable didn't sort %d ints", n)
147 }
148 if !data.inOrder() {
149 t.Errorf("Stable wasn't stable on %d ints", n)
150 }
151
152 // already sorted
153 data.initB()
154 SortStableFunc(data, intPairCmp)
155 if !IsSortedFunc(data, intPairCmp) {
156 t.Errorf("Stable shuffled sorted %d ints (order)", n)
157 }
158 if !data.inOrder() {
159 t.Errorf("Stable shuffled sorted %d ints (stability)", n)
160 }
161
162 // sorted reversed
163 for i := 0; i < len(data); i++ {
164 data[i].a = len(data) - i
165 }
166 data.initB()
167 SortStableFunc(data, intPairCmp)
168 if !IsSortedFunc(data, intPairCmp) {
169 t.Errorf("Stable didn't sort %d ints", n)
170 }
171 if !data.inOrder() {
172 t.Errorf("Stable wasn't stable on %d ints", n)
173 }
174 }
175
176 type S struct {
177 a int
178 b string
179 }
180
181 func cmpS(s1, s2 S) int {
182 return cmp.Compare(s1.a, s2.a)
183 }
184
185 func TestMinMax(t *testing.T) {
186 intCmp := func(a, b int) int { return a - b }
187
188 tests := []struct {
189 data []int
190 wantMin int
191 wantMax int
192 }{
193 {[]int{7}, 7, 7},
194 {[]int{1, 2}, 1, 2},
195 {[]int{2, 1}, 1, 2},
196 {[]int{1, 2, 3}, 1, 3},
197 {[]int{3, 2, 1}, 1, 3},
198 {[]int{2, 1, 3}, 1, 3},
199 {[]int{2, 2, 3}, 2, 3},
200 {[]int{3, 2, 3}, 2, 3},
201 {[]int{0, 2, -9}, -9, 2},
202 }
203 for _, tt := range tests {
204 t.Run(fmt.Sprintf("%v", tt.data), func(t *testing.T) {
205 gotMin := Min(tt.data)
206 if gotMin != tt.wantMin {
207 t.Errorf("Min got %v, want %v", gotMin, tt.wantMin)
208 }
209
210 gotMinFunc := MinFunc(tt.data, intCmp)
211 if gotMinFunc != tt.wantMin {
212 t.Errorf("MinFunc got %v, want %v", gotMinFunc, tt.wantMin)
213 }
214
215 gotMax := Max(tt.data)
216 if gotMax != tt.wantMax {
217 t.Errorf("Max got %v, want %v", gotMax, tt.wantMax)
218 }
219
220 gotMaxFunc := MaxFunc(tt.data, intCmp)
221 if gotMaxFunc != tt.wantMax {
222 t.Errorf("MaxFunc got %v, want %v", gotMaxFunc, tt.wantMax)
223 }
224 })
225 }
226
227 svals := []S{
228 {1, "a"},
229 {2, "a"},
230 {1, "b"},
231 {2, "b"},
232 }
233
234 gotMin := MinFunc(svals, cmpS)
235 wantMin := S{1, "a"}
236 if gotMin != wantMin {
237 t.Errorf("MinFunc(%v) = %v, want %v", svals, gotMin, wantMin)
238 }
239
240 gotMax := MaxFunc(svals, cmpS)
241 wantMax := S{2, "a"}
242 if gotMax != wantMax {
243 t.Errorf("MaxFunc(%v) = %v, want %v", svals, gotMax, wantMax)
244 }
245 }
246
247 func TestMinMaxNaNs(t *testing.T) {
248 fs := []float64{1.0, 999.9, 3.14, -400.4, -5.14}
249 if Min(fs) != -400.4 {
250 t.Errorf("got min %v, want -400.4", Min(fs))
251 }
252 if Max(fs) != 999.9 {
253 t.Errorf("got max %v, want 999.9", Max(fs))
254 }
255
256 // No matter which element of fs is replaced with a NaN, both Min and Max
257 // should propagate the NaN to their output.
258 for i := 0; i < len(fs); i++ {
259 testfs := Clone(fs)
260 testfs[i] = math.NaN()
261
262 fmin := Min(testfs)
263 if !math.IsNaN(fmin) {
264 t.Errorf("got min %v, want NaN", fmin)
265 }
266
267 fmax := Max(testfs)
268 if !math.IsNaN(fmax) {
269 t.Errorf("got max %v, want NaN", fmax)
270 }
271 }
272 }
273
274 func TestMinMaxPanics(t *testing.T) {
275 intCmp := func(a, b int) int { return a - b }
276 emptySlice := []int{}
277
278 if !panics(func() { Min(emptySlice) }) {
279 t.Errorf("Min([]): got no panic, want panic")
280 }
281
282 if !panics(func() { Max(emptySlice) }) {
283 t.Errorf("Max([]): got no panic, want panic")
284 }
285
286 if !panics(func() { MinFunc(emptySlice, intCmp) }) {
287 t.Errorf("MinFunc([]): got no panic, want panic")
288 }
289
290 if !panics(func() { MaxFunc(emptySlice, intCmp) }) {
291 t.Errorf("MaxFunc([]): got no panic, want panic")
292 }
293 }
294
295 func TestBinarySearch(t *testing.T) {
296 str1 := []string{"foo"}
297 str2 := []string{"ab", "ca"}
298 str3 := []string{"mo", "qo", "vo"}
299 str4 := []string{"ab", "ad", "ca", "xy"}
300
301 // slice with repeating elements
302 strRepeats := []string{"ba", "ca", "da", "da", "da", "ka", "ma", "ma", "ta"}
303
304 // slice with all element equal
305 strSame := []string{"xx", "xx", "xx"}
306
307 tests := []struct {
308 data []string
309 target string
310 wantPos int
311 wantFound bool
312 }{
313 {[]string{}, "foo", 0, false},
314 {[]string{}, "", 0, false},
315
316 {str1, "foo", 0, true},
317 {str1, "bar", 0, false},
318 {str1, "zx", 1, false},
319
320 {str2, "aa", 0, false},
321 {str2, "ab", 0, true},
322 {str2, "ad", 1, false},
323 {str2, "ca", 1, true},
324 {str2, "ra", 2, false},
325
326 {str3, "bb", 0, false},
327 {str3, "mo", 0, true},
328 {str3, "nb", 1, false},
329 {str3, "qo", 1, true},
330 {str3, "tr", 2, false},
331 {str3, "vo", 2, true},
332 {str3, "xr", 3, false},
333
334 {str4, "aa", 0, false},
335 {str4, "ab", 0, true},
336 {str4, "ac", 1, false},
337 {str4, "ad", 1, true},
338 {str4, "ax", 2, false},
339 {str4, "ca", 2, true},
340 {str4, "cc", 3, false},
341 {str4, "dd", 3, false},
342 {str4, "xy", 3, true},
343 {str4, "zz", 4, false},
344
345 {strRepeats, "da", 2, true},
346 {strRepeats, "db", 5, false},
347 {strRepeats, "ma", 6, true},
348 {strRepeats, "mb", 8, false},
349
350 {strSame, "xx", 0, true},
351 {strSame, "ab", 0, false},
352 {strSame, "zz", 3, false},
353 }
354 for _, tt := range tests {
355 t.Run(tt.target, func(t *testing.T) {
356 {
357 pos, found := BinarySearch(tt.data, tt.target)
358 if pos != tt.wantPos || found != tt.wantFound {
359 t.Errorf("BinarySearch got (%v, %v), want (%v, %v)", pos, found, tt.wantPos, tt.wantFound)
360 }
361 }
362
363 {
364 pos, found := BinarySearchFunc(tt.data, tt.target, strings.Compare)
365 if pos != tt.wantPos || found != tt.wantFound {
366 t.Errorf("BinarySearchFunc got (%v, %v), want (%v, %v)", pos, found, tt.wantPos, tt.wantFound)
367 }
368 }
369 })
370 }
371 }
372
373 func TestBinarySearchInts(t *testing.T) {
374 data := []int{20, 30, 40, 50, 60, 70, 80, 90}
375 tests := []struct {
376 target int
377 wantPos int
378 wantFound bool
379 }{
380 {20, 0, true},
381 {23, 1, false},
382 {43, 3, false},
383 {80, 6, true},
384 }
385 for _, tt := range tests {
386 t.Run(strconv.Itoa(tt.target), func(t *testing.T) {
387 {
388 pos, found := BinarySearch(data, tt.target)
389 if pos != tt.wantPos || found != tt.wantFound {
390 t.Errorf("BinarySearch got (%v, %v), want (%v, %v)", pos, found, tt.wantPos, tt.wantFound)
391 }
392 }
393
394 {
395 cmp := func(a, b int) int {
396 return a - b
397 }
398 pos, found := BinarySearchFunc(data, tt.target, cmp)
399 if pos != tt.wantPos || found != tt.wantFound {
400 t.Errorf("BinarySearchFunc got (%v, %v), want (%v, %v)", pos, found, tt.wantPos, tt.wantFound)
401 }
402 }
403 })
404 }
405 }
406
407 func TestBinarySearchFloats(t *testing.T) {
408 data := []float64{math.NaN(), -0.25, 0.0, 1.4}
409 tests := []struct {
410 target float64
411 wantPos int
412 wantFound bool
413 }{
414 {math.NaN(), 0, true},
415 {math.Inf(-1), 1, false},
416 {-0.25, 1, true},
417 {0.0, 2, true},
418 {1.4, 3, true},
419 {1.5, 4, false},
420 }
421 for _, tt := range tests {
422 t.Run(fmt.Sprintf("%v", tt.target), func(t *testing.T) {
423 {
424 pos, found := BinarySearch(data, tt.target)
425 if pos != tt.wantPos || found != tt.wantFound {
426 t.Errorf("BinarySearch got (%v, %v), want (%v, %v)", pos, found, tt.wantPos, tt.wantFound)
427 }
428 }
429 })
430 }
431 }
432
433 func TestBinarySearchFunc(t *testing.T) {
434 data := []int{1, 10, 11, 2} // sorted lexicographically
435 cmp := func(a int, b string) int {
436 return strings.Compare(strconv.Itoa(a), b)
437 }
438 pos, found := BinarySearchFunc(data, "2", cmp)
439 if pos != 3 || !found {
440 t.Errorf("BinarySearchFunc(%v, %q, cmp) = %v, %v, want %v, %v", data, "2", pos, found, 3, true)
441 }
442 }