Debian Codegraph @

radixsort_test.go

raw
1 // Copyright 2009 The Go Authors.
2 // Copyright 2014-5 Randall Farmer.
3 // All rights reserved.
4
5 // Use of this source code is governed by a BSD-style
6 // license that can be found in the LICENSE file.
7
8 package sorts_test
9
10 import (
11 "bytes"
12 "fmt"
13 "math/rand"
14 "sort"
15 "strconv"
16 "testing"
17
18 . "github.com/twotwotwo/sorts"
19 . "github.com/twotwotwo/sorts/sortutil"
20 )
21
22 // check the IsSorted checks with a type that will never look sorted
23 type unsortableInts struct{ IntSlice }
24
25 func (u unsortableInts) Less(i, j int) bool { return j&1 == 1 }
26
27 type unsortableUints struct{ UintSlice }
28
29 func (u unsortableUints) Less(i, j int) bool { return j&1 == 1 }
30
31 type unsortableStrings struct{ StringSlice }
32
33 func (u unsortableStrings) Less(i, j int) bool { return j&1 == 1 }
34
35 type unsortableBytes struct{ BytesSlice }
36
37 func (u unsortableBytes) Less(i, j int) bool { return j&1 == 1 }
38
39 // more unsortable types, but now it's detectably because Key disagrees with Less
40 type miskeyedInts struct{ IntSlice }
41
42 func (u miskeyedInts) Less(i, j int) bool { return u.IntSlice[j] < u.IntSlice[i] }
43
44 type miskeyedUints struct{ UintSlice }
45
46 func (u miskeyedUints) Less(i, j int) bool { return u.UintSlice[j] < u.UintSlice[i] }
47
48 type miskeyedStrings struct{ StringSlice }
49
50 func (u miskeyedStrings) Less(i, j int) bool { return u.StringSlice[j] < u.StringSlice[i] }
51
52 type miskeyedBytes struct{ BytesSlice }
53
54 func (u miskeyedBytes) Less(i, j int) bool {
55 return bytes.Compare(u.BytesSlice[j], u.BytesSlice[i]) == -1
56 }
57
58 func mustPanic(t *testing.T, name string, f func()) {
59 defer func() { _ = recover() }()
60 f()
61 t.Errorf("expected a panic on unsortable datatype %s", name)
62 }
63
64 func TestSortCheck(t *testing.T) {
65 // only the new code, not qSort, panics if it's wrong
66 defer SetQSortCutoff(SetQSortCutoff(1))
67 if !Checking() {
68 return
69 }
70 mustPanic(t, "unsortableInts", func() {
71 ByInt64(unsortableInts{IntSlice{1, 1, 1}})
72 })
73 mustPanic(t, "unsortableUints", func() {
74 ByUint64(unsortableUints{UintSlice{1, 1, 1}})
75 })
76 mustPanic(t, "unsortableStrings", func() {
77 ByString(unsortableStrings{StringSlice{"", "", ""}})
78 })
79 mustPanic(t, "unsortableBytes", func() {
80 ByBytes(unsortableBytes{BytesSlice{[]byte{}, []byte{}, []byte{}}})
81 })
82 mustPanic(t, "miskeyedInts", func() {
83 forceRadix(func() {
84 ByInt64(miskeyedInts{IntSlice{1, 2, 3}})
85 })
86 })
87 mustPanic(t, "miskeyedUints", func() {
88 forceRadix(func() {
89 ByUint64(miskeyedUints{UintSlice{1, 2, 3}})
90 })
91 })
92 mustPanic(t, "miskeyedStrings", func() {
93 forceRadix(func() {
94 ByString(miskeyedStrings{StringSlice{"a", "b", "c"}})
95 })
96 })
97 mustPanic(t, "miskeyedBytes", func() {
98 forceRadix(func() {
99 ByBytes(miskeyedBytes{BytesSlice{[]byte{'a'}, []byte{'b'}, []byte{'c'}}})
100 })
101 })
102 }
103
104 func TestFlip(t *testing.T) {
105 data1, expected1 := [...]int{1, 2, 3, 4, 5}, [...]int{5, 4, 3, 2, 1}
106 Flip(IntSlice(data1[:]))
107 if data1 != expected1 {
108 t.Errorf("Flip didn't flip!")
109 }
110 data2, expected2 := [...]int{1, 2}, [...]int{2, 1}
111 Flip(IntSlice(data2[:]))
112 if data2 != expected2 {
113 t.Errorf("Flip didn't flip!")
114 }
115 Flip(IntSlice(nil)) // just shouldn't panic
116 }
117
118 func TestEmpty(t *testing.T) {
119 Quicksort(IntSlice(nil))
120 IntSlice(nil).Sort()
121 UintSlice(nil).Sort()
122 StringSlice(nil).Sort()
123 BytesSlice(nil).Sort()
124 IntSlice(nil).Search(0)
125 StringSlice(nil).Search("")
126 BytesSlice(nil).Search([]byte(nil))
127 }
128
129 func TestTiny(t *testing.T) {
130 Quicksort(IntSlice([]int{1}))
131 IntSlice([]int{1}).Sort()
132 UintSlice([]uint{1}).Sort()
133 StringSlice([]string{""}).Sort()
134 BytesSlice([][]byte{nil}).Sort()
135 Quicksort(IntSlice([]int{1, 1}))
136 IntSlice([]int{1, 1}).Sort()
137 UintSlice([]uint{1, 1}).Sort()
138 StringSlice([]string{"", ""}).Sort()
139 BytesSlice([][]byte{nil, nil}).Sort()
140 }
141
142 func TestSortLarge_Random(t *testing.T) {
143 n := 1000000
144 if testing.Short() {
145 n /= 100
146 }
147 data := make([]int, n)
148 for i := 0; i < len(data); i++ {
149 data[i] = rand.Intn(100)
150 }
151 if IntsAreSorted(data) {
152 t.Fatalf("terrible rand.rand")
153 }
154 Ints(data)
155 if !IntsAreSorted(data) {
156 t.Errorf("sort didn't sort - 1M ints")
157 }
158 }
159
160 // RoundedKeyInt64s wraps sortutil.Int64Slice to return the same key for
161 // some distinct values, to test using Less for a tiebreaker when using
162 // int64 keys.
163 type RoundedKeyInt64s struct { Int64Slice }
164 func (r RoundedKeyInt64s) Key(i int) int64 { return r.Int64Slice[i] / 10 }
165
166 // RoundedKeyUint64s wraps sortutil.Uint64Slice to return the same key for
167 // some distinct values, to test using Less for a tiebreaker when using
168 // uint64 keys.
169 type RoundedKeyUint64s struct { Uint64Slice }
170 func (r RoundedKeyUint64s) Key(i int) uint64 { return r.Uint64Slice[i] / 10 }
171
172 // TruncatedKeyStrings wraps sortutil.StringSlice to truncate the value
173 // returned by Key, to test using Less for a tiebreaker when using string
174 // keys.
175 type TruncatedKeyStrings struct { StringSlice }
176 func (r TruncatedKeyStrings) Key(i int) string { return r.StringSlice[i][:1] }
177
178 // TruncatedKeyBytes wraps sortutil.BytesSlice to truncate the value
179 // returned by Key, to test using Less for a tiebreaker when using []bytes
180 // keys.
181 type TruncatedKeyBytes struct { BytesSlice }
182 func (r TruncatedKeyBytes) Key(i int) []byte { return r.BytesSlice[i][:1] }
183
184 func TestTiebreakEqualKeys(t *testing.T) {
185 n := 1000
186 // give radixsort as many chances to fail as possible
187 defer SetQSortCutoff(SetQSortCutoff(1))
188
189 data := make([]int64, n)
190 for i := 0; i < len(data); i++ {
191 data[i] = rand.Int63n(100)
192 }
193 if Int64sAreSorted(data) {
194 t.Errorf("no random test data")
195 }
196 ByInt64(RoundedKeyInt64s{Int64Slice(data)})
197 if !Int64sAreSorted(data) {
198 t.Errorf("sort didn't sort - 1K rounded ints")
199 }
200
201 uintData := make([]uint64, n)
202 for i := 0; i < len(uintData); i++ {
203 uintData[i] = uint64(rand.Int63n(100))
204 }
205 if Uint64sAreSorted(uintData) {
206 t.Errorf("no random test data")
207 }
208 ByUint64(RoundedKeyUint64s{Uint64Slice(uintData)})
209 if !Uint64sAreSorted(uintData) {
210 t.Errorf("sort didn't sort - 1K rounded uints")
211 }
212
213 stringData := make([]string, n)
214 for i := 0; i < len(stringData); i++ {
215 stringData[i] = strconv.Itoa(rand.Intn(100))
216 }
217 if StringsAreSorted(stringData) {
218 t.Errorf("no random test data")
219 }
220 ByString(TruncatedKeyStrings{StringSlice(stringData)})
221 if !StringsAreSorted(stringData) {
222 t.Errorf("sort didn't sort - 1K truncated strings")
223 }
224
225 bytesData := make([][]byte, n)
226 for i := 0; i < len(bytesData); i++ {
227 bytesData[i] = []byte(strconv.Itoa(rand.Intn(100)))
228 }
229 if BytesAreSorted(bytesData) {
230 t.Errorf("no random test data")
231 }
232 ByBytes(TruncatedKeyBytes{BytesSlice(bytesData)})
233 if !BytesAreSorted(bytesData) {
234 t.Errorf("sort didn't sort - 1K truncated []bytes")
235 }
236 }
237
238 func BenchmarkSortString1K(b *testing.B) {
239 b.StopTimer()
240 for i := 0; i < b.N; i++ {
241 data := make([]string, 1<<10)
242 for i := 0; i < len(data); i++ {
243 data[i] = strconv.Itoa(i ^ 0x2cc)
244 }
245 b.StartTimer()
246 Strings(data)
247 b.StopTimer()
248 }
249 }
250
251 func BenchmarkSortInt1K(b *testing.B) {
252 b.StopTimer()
253 for i := 0; i < b.N; i++ {
254 data := make([]int, 1<<10)
255 for i := 0; i < len(data); i++ {
256 data[i] = i ^ 0x2cc
257 }
258 b.StartTimer()
259 Ints(data)
260 b.StopTimer()
261 }
262 }
263
264 func BenchmarkSortInt64K(b *testing.B) {
265 b.StopTimer()
266 for i := 0; i < b.N; i++ {
267 data := make([]int, 1<<16)
268 for i := 0; i < len(data); i++ {
269 data[i] = i ^ 0xcccc
270 }
271 b.StartTimer()
272 Ints(data)
273 b.StopTimer()
274 }
275 }
276
277 const (
278 _Sawtooth = iota
279 _Rand
280 _Stagger
281 _Plateau
282 _Shuffle
283 _NDist
284 )
285
286 const (
287 _Copy = iota
288 _Reverse
289 _ReverseFirstHalf
290 _ReverseSecondHalf
291 _Sorted
292 _Dither
293 _NMode
294 )
295
296 type testingData struct {
297 desc string
298 t *testing.T
299 data []int
300 maxswap int // number of swaps allowed
301 ncmp, nswap int
302 }
303
304 func (d *testingData) Len() int { return len(d.data) }
305 func (d *testingData) Key(i int) int64 { return int64(d.data[i]) }
306 func (d *testingData) Less(i, j int) bool {
307 d.ncmp++
308 return d.data[i] < d.data[j]
309 }
310 func (d *testingData) Swap(i, j int) {
311 if d.nswap >= d.maxswap {
312 d.t.Errorf("%s: used %d swaps sorting slice of %d", d.desc, d.nswap, len(d.data))
313 d.t.FailNow()
314 }
315 d.nswap++
316 d.data[i], d.data[j] = d.data[j], d.data[i]
317 }
318
319 func min(a, b int) int {
320 if a < b {
321 return a
322 }
323 return b
324 }
325
326 func lg(n int) int {
327 i := 0
328 for 1<<uint(i) < n {
329 i++
330 }
331 return i
332 }
333
334 func testBentleyMcIlroy(t *testing.T, sort func(sort.Interface), maxswap func(int) int) {
335 sizes := []int{100, 1023, 1024, 1025}
336 if testing.Short() {
337 sizes = []int{100, 127, 128, 129}
338 }
339 dists := []string{"sawtooth", "rand", "stagger", "plateau", "shuffle"}
340 modes := []string{"copy", "reverse", "reverse1", "reverse2", "sort", "dither"}
341 var tmp1, tmp2 [1025]int
342 for _, n := range sizes {
343 for m := 1; m < 2*n; m *= 2 {
344 for dist := 0; dist < _NDist; dist++ {
345 j := 0
346 k := 1
347 data := tmp1[0:n]
348 for i := 0; i < n; i++ {
349 switch dist {
350 case _Sawtooth:
351 data[i] = i % m
352 case _Rand:
353 data[i] = rand.Intn(m)
354 case _Stagger:
355 data[i] = (i*m + i) % n
356 case _Plateau:
357 data[i] = min(i, m)
358 case _Shuffle:
359 if rand.Intn(m) != 0 {
360 j += 2
361 data[i] = j
362 } else {
363 k += 2
364 data[i] = k
365 }
366 }
367 }
368
369 mdata := tmp2[0:n]
370 for mode := 0; mode < _NMode; mode++ {
371 switch mode {
372 case _Copy:
373 for i := 0; i < n; i++ {
374 mdata[i] = data[i]
375 }
376 case _Reverse:
377 for i := 0; i < n; i++ {
378 mdata[i] = data[n-i-1]
379 }
380 case _ReverseFirstHalf:
381 for i := 0; i < n/2; i++ {
382 mdata[i] = data[n/2-i-1]
383 }
384 for i := n / 2; i < n; i++ {
385 mdata[i] = data[i]
386 }
387 case _ReverseSecondHalf:
388 for i := 0; i < n/2; i++ {
389 mdata[i] = data[i]
390 }
391 for i := n / 2; i < n; i++ {
392 mdata[i] = data[n-(i-n/2)-1]
393 }
394 case _Sorted:
395 for i := 0; i < n; i++ {
396 mdata[i] = data[i]
397 }
398 // Ints is known to be correct
399 // because mode Sort runs after mode _Copy.
400 Ints(mdata)
401 case _Dither:
402 for i := 0; i < n; i++ {
403 mdata[i] = data[i] + i%5
404 }
405 }
406
407 desc := fmt.Sprintf("n=%d m=%d dist=%s mode=%s", n, m, dists[dist], modes[mode])
408 d := &testingData{desc: desc, t: t, data: mdata[0:n], maxswap: maxswap(n)}
409 sort(d)
410 // Uncomment if you are trying to improve the number of compares/swaps.
411 //t.Logf("%s: ncmp=%d, nswp=%d", desc, d.ncmp, d.nswap)
412
413 // If we were testing C qsort, we'd have to make a copy
414 // of the slice and sort it ourselves and then compare
415 // x against it, to ensure that qsort was only permuting
416 // the data, not (for example) overwriting it with zeros.
417 //
418 // In go, we don't have to be so paranoid: since the only
419 // mutating method Sort can call is TestingData.swap,
420 // it suffices here just to check that the final slice is sorted.
421 if !IntsAreSorted(mdata) {
422 t.Errorf("%s: ints not sorted", desc)
423 t.Errorf("\t%v", mdata)
424 t.FailNow()
425 }
426 }
427 }
428 }
429 }
430 }
431
432 func byInt64Wrapper(d sort.Interface) {
433 ByInt64(d.(Int64Interface))
434 }
435
436 func TestSortBM(t *testing.T) {
437 testBentleyMcIlroy(t, byInt64Wrapper, func(n int) int { return n * lg(n) * 12 / 10 })
438 }
439
440 func TestManySortBM(t *testing.T) {
441 testBentleyMcIlroy(t, manySortWrapper, func(n int) int { return n * lg(n) * 12 / 10 })
442 }
443
444 func TestHeapsortBM(t *testing.T) {
445 testBentleyMcIlroy(t, Heapsort, func(n int) int { return n * lg(n) * 12 / 10 })
446 }
447
448 // TestBackshift checks that radix sorting still works on data that trips up
449 // guessIntShift because it varies in a high bit, but only in a value that
450 // guessIntShift sampling misses
451 func TestBackshift(t *testing.T) {
452 funnyData := [1e3]int{1: -1}
453 funny := IntSlice(funnyData[:])
454 if GuessIntShift(funny, len(funny)) > 0 {
455 panic("guessIntShift got smarter")
456 }
457 forceRadix(func() { multiSort(funnyData[:]) })
458 if !sort.IsSorted(funny) {
459 t.Errorf("backshift data didn't sort")
460 }
461 }
462
463 // TestFwdShift uses data that lets the radix sort shift past some bits in
464 // the middle; it might catch if it broke the sort.
465 func TestFwdShift(t *testing.T) {
466 // an upper bit varies, lower byte varies, but bytes in between don't
467 funnyData := []int{0x40000000, 23, 59, 38, 38, 6, 12, 9, 3, 4, 1, 49, 9, 63}
468 funny := IntSlice(funnyData)
469 forceRadix(func() { multiSort(funnyData) })
470 if !sort.IsSorted(funny) {
471 t.Errorf("forward-shift data didn't sort")
472 }
473 }
474
475 // TestBrokenPrefix uses string and byte data where *most* input shares a
476 // common prefix except for one value that breaks the pattern at each byte
477 // position. It's a bad case for the "everything was in one bucket"
478 // optimization, but we're merely looking for it not to barf (where barfing
479 // would be sort time exploding or data not sorting).
480 func TestBrokenPrefix(t *testing.T) {
481 src := [128]byte{}
482 src[64] = 1
483 data := [10000][]byte{}
484 for i := range data {
485 data[i] = src[:]
486 }
487 // last 64 entries have a 1 in a pseudorandom position, breaking the
488 // pattern
489 for i := 10000 - 64; i < 10000; i++ {
490 data[i] = src[64-((i*11)%64):]
491 }
492 forceRadix(BytesSlice(data[:]).Sort)
493 if !BytesAreSorted(data[:]) {
494 t.Errorf("broken-prefix data didn't sort")
495 }
496
497 srcStr := string(src[:])
498 dataStr := [10000]string{}
499 for i := range dataStr {
500 dataStr[i] = srcStr
501 }
502 for i := 10000 - 64; i < 10000; i++ {
503 data[i] = src[64-((i*11)%64):]
504 }
505 forceRadix(StringSlice(dataStr[:]).Sort)
506 if !StringsAreSorted(dataStr[:]) {
507 t.Errorf("broken-prefix data didn't sort")
508 }
509 }
510
511 // TestShifts uses integer data consisting of a 1 bit in a random position.
512 // It's like TestBrokenPrefix for integer data.
513 func TestShifts(t *testing.T) {
514 data := make([]uint64, 10000)
515 for i := range data {
516 data[i] = 1 << uint((i*19)%64)
517 }
518 forceRadix(Uint64Slice(data).Sort)
519 if !Uint64sAreSorted(data) {
520 t.Errorf("shifts data didn't sort")
521 }
522 }
523
524 // TestMaxProcs makes sure forcing a serial sort doesn't break everything.
525 func TestMaxProcs(t *testing.T) {
526 defer func(old int) { MaxProcs = old }(MaxProcs)
527 MaxProcs = 1
528
529 // this is TestLarge_Random
530 n := 1000000
531 if testing.Short() {
532 n /= 100
533 }
534 data := make([]int, n)
535 for i := 0; i < len(data); i++ {
536 data[i] = rand.Intn(100)
537 }
538 manySort(data)
539 if !IntsAreSorted(data) {
540 t.Errorf("serial sort failed")
541 }
542 }
543
544 // TestSortByLength uses data that only varies in how many \0 bytes values
545 // contain.
546 func TestSortByLength(t *testing.T) {
547 src := [128]byte{}
548 data := [10000][]byte{}
549 for i := range data {
550 data[i] = src[:(i*19)%128]
551 }
552 forceRadix(BytesSlice(data[:]).Sort)
553 if !BytesAreSorted(data[:]) {
554 t.Errorf("sort-by-length data didn't sort")
555 }
556
557 srcStr := string(src[:])
558 dataStr := [10000]string{}
559 for i := range dataStr {
560 dataStr[i] = srcStr[:(i*19)%128]
561 }
562 forceRadix(StringSlice(dataStr[:]).Sort)
563 if !StringsAreSorted(dataStr[:]) {
564 t.Errorf("sort-by-length data didn't sort")
565 }
566 }
567
568 var countOpsSizes = []int{1e2, 3e2, 1e3, 3e3, 1e4, 3e4, 1e5, 3e5, 1e6}
569
570 func countOps(t *testing.T, algo func(sort.Interface), name string) {
571 sizes := countOpsSizes
572 if testing.Short() {
573 sizes = sizes[:5]
574 }
575 if !testing.Verbose() {
576 t.Skip("Counting skipped as non-verbose mode.")
577 }
578 for _, n := range sizes {
579 td := testingData{
580 desc: name,
581 t: t,
582 data: make([]int, n),
583 maxswap: 1<<31 - 1,
584 }
585 for i := 0; i < n; i++ {
586 td.data[i] = rand.Intn(n / 5)
587 }
588 algo(&td)
589 t.Logf("%s %8d elements: %11d Swap, %10d Less", name, n, td.nswap, td.ncmp)
590 }
591 }
592
593 func TestCountSortOps(t *testing.T) { countOps(t, byInt64Wrapper, "Sort ") }
594
595 func bench(b *testing.B, size int, algo func(sort.Interface), name string) {
596 b.StopTimer()
597 data := make(IntSlice, size)
598 x := ^uint32(0)
599 for i := 0; i < b.N; i++ {
600 for n := size - 3; n <= size+3; n++ {
601 for i := 0; i < len(data); i++ {
602 x += x
603 x ^= 1
604 if int32(x) < 0 {
605 x ^= 0x88888eef
606 }
607 data[i] = int(x % uint32(n/5))
608 }
609 b.StartTimer()
610 algo(data)
611 b.StopTimer()
612 if !sort.IsSorted(data) {
613 b.Errorf("%s did not sort %d ints", name, n)
614 }
615 }
616 }
617 }
618
619 // This is based on the "antiquicksort" implementation by M. Douglas McIlroy.
620 // See http://www.cs.dartmouth.edu/~doug/mdmspe.pdf for more info.
621 type adversaryTestingData struct {
622 data []int
623 keys map[int]int
624 candidate int
625 }
626
627 func (d *adversaryTestingData) Len() int { return len(d.data) }
628
629 func (d *adversaryTestingData) Less(i, j int) bool {
630 if _, present := d.keys[i]; !present {
631 if _, present := d.keys[j]; !present {
632 if i == d.candidate {
633 d.keys[i] = len(d.keys)
634 } else {
635 d.keys[j] = len(d.keys)
636 }
637 }
638 }
639
640 if _, present := d.keys[i]; !present {
641 d.candidate = i
642 return false
643 }
644 if _, present := d.keys[j]; !present {
645 d.candidate = j
646 return true
647 }
648
649 return d.keys[i] >= d.keys[j]
650 }
651
652 func (d *adversaryTestingData) Swap(i, j int) {
653 d.data[i], d.data[j] = d.data[j], d.data[i]
654 }
655
656 func TestAdversary(t *testing.T) {
657 const size = 100
658 data := make([]int, size)
659 for i := 0; i < size; i++ {
660 data[i] = i
661 }
662
663 d := &adversaryTestingData{data, make(map[int]int), 0}
664 Quicksort(d) // This should degenerate to heapsort.
665 defer SetMinOffload(SetMinOffload(1))
666 d = &adversaryTestingData{data, make(map[int]int), 0}
667 Quicksort(d)
668 }
669
670 func BenchmarkSort1e2(b *testing.B) { bench(b, 1e2, byInt64Wrapper, "Sort") }
671 func BenchmarkSort1e4(b *testing.B) { bench(b, 1e4, byInt64Wrapper, "Sort") }
672 func BenchmarkSort1e6(b *testing.B) { bench(b, 1e6, byInt64Wrapper, "Sort") }