File: radixsort.go

package info (click to toggle)
golang-github-twotwotwo-sorts 0.0~git20160814.bf5c1f2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 172 kB
  • sloc: makefile: 2
file content (534 lines) | stat: -rw-r--r-- 12,486 bytes parent folder | download
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
// Copyright 2014-5 Randall Farmer. All rights reserved.

// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package sorts

import (
	"bytes"
	"sort"
)

const radix = 8
const mask = (1 << radix) - 1

// qSortCutoff is when we bail out to a quicksort. It's changed to 1 for
// certain tests so we can more easily exercise the radix sorting.  This was
// around the break-even point in some sloppy tests.
var qSortCutoff = 1 << 7

const keyPanicMessage = "sort failed: Key and Less aren't consistent with each other"
const keyUint64Help = " (for float data, sortutil Key functions may help resolve this)"
const panicMessage = "sort failed: could be a data race, a bug in package sorts, or a subtle bug in the interface implementation"

// maxRadixDepth limits how deeply the radix part of string sorts can
// recurse before we bail to quicksort.  Each recursion uses 2KB stack.
const maxRadixDepth = 32

// task describes a range of data to be sorted and additional
// information the sorter needs: bitshift in a numeric sort, byte offset in
// a string sort, or maximum depth (expressed as -maxDepth-1) for a
// quicksort.
type task struct{ offs, pos, end int }

// ByUint64 sorts data by a uint64 key.
func ByUint64(data Uint64Interface) {
	l := data.Len()
	if l < qSortCutoff {
		qSort(data, 0, l)
		return
	}
	
	shift := guessIntShift(data, l)
	parallelSort(data, radixSortUint64, task{offs: int(shift), end: l})

	// check results if we radix sorted!
	for i := 1; i < l; i++ {
		if data.Less(i, i-1) {
			if data.Key(i) > data.Key(i-1) {
				panic(keyPanicMessage + keyUint64Help)
			}
			panic(panicMessage)
		}
	}
}

// int64Key generates a uint64 from an int64
func int64Key(i int64) uint64 { return uint64(i) ^ 1<<63 }

// intwrapper tunrs an Int64Interface into a Uint64Interface for
// guessIntShift
type intwrapper struct{ Int64Interface }

func (iw intwrapper) Key(i int) uint64 {
	return int64Key(iw.Int64Interface.Key(i))
}

// ByInt64 sorts data by an int64 key.
func ByInt64(data Int64Interface) {
	l := data.Len()
	if l < qSortCutoff {
		qSort(data, 0, l)
		return
	}

	shift := guessIntShift(intwrapper{data}, l)
	parallelSort(data, radixSortInt64, task{offs: int(shift), end: l})

	// check results!
	for i := 1; i < l; i++ {
		if data.Less(i, i-1) {
			if data.Key(i) > data.Key(i-1) {
				panic(keyPanicMessage + keyUint64Help)
			}
			panic(panicMessage)
		}
	}
}

// ByString sorts data by a string key.
func ByString(data StringInterface) {
	l := data.Len()
	if l < qSortCutoff {
		qSort(data, 0, l)
		return
	}

	parallelSort(data, radixSortString, task{end: l})

	// check results if we radix sorted!
	for i := 1; i < l; i++ {
		if data.Less(i, i-1) {
			if data.Key(i) > data.Key(i-1) {
				panic(keyPanicMessage)
			}
			panic(panicMessage)
		}
	}
}

// ByBytes sorts data by a []byte key.
func ByBytes(data BytesInterface) {
	l := data.Len()
	if l < qSortCutoff {
		qSort(data, 0, l)
		return
	}

	parallelSort(data, radixSortBytes, task{end: l})

	// check results if we radix sorted!
	for i := 1; i < l; i++ {
		if data.Less(i, i-1) {
			if bytes.Compare(data.Key(i), data.Key(i-1)) > 0 {
				panic(keyPanicMessage)
			}
			panic(panicMessage)
		}
	}
}

// guessIntShift saves a pass when the data is distributed roughly uniformly
// in a small range (think shuffled indices into a small array), and rarely
// hurts much otherwise: either it just returns 64-radix quickly, or it
// returns too small a shift and the sort notices after one useless counting
// pass.
func guessIntShift(data Uint64Interface, l int) uint {
	step := l >> 5
	if l > 1<<16 {
		step = l >> 8
	}
	if step == 0 { // only for tests w/qSortCutoff lowered
		step = 1
	}
	min := data.Key(l - 1)
	max := min
	for i := 0; i < l; i += step {
		k := data.Key(i)
		if k < min {
			min = k
		}
		if k > max {
			max = k
		}
	}
	diff := min ^ max
	log2diff := 0
	for diff != 0 {
		log2diff++
		diff >>= 1
	}
	shiftGuess := log2diff - radix
	if shiftGuess < 0 {
		return 0
	}
	return uint(shiftGuess)
}

/*
Thanks to (and please refer to):

Victor J. Duvanenko, "Parallel In-Place Radix Sort Simplified", 2011, at
http://www.drdobbs.com/parallel/parallel-in-place-radix-sort-simplified/229000734
for lots of practical discussion of performance

Michael Herf, "Radix Tricks", 2001, at
http://stereopsis.com/radix.html
for the idea for Float32Key()/Float64Key() (via Pierre Tardiman, "Radix Sort
Revisited", 2000, at http://codercorner.com/RadixSortRevisited.htm) and more
performance talk.

A handy slide deck summarizing Robert Sedgewick and Kevin Wayne's Algorithms
on string sorts:
http://algs4.cs.princeton.edu/lectures/51StringSorts.pdf
for a grounding in string sorts and pointer to American flag sort

McIlroy, Bostic, and McIlroy, "Engineering Radix Sort", 1993 at
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6990
for laying out American flag sort

- We're not using American flag sort's trick of keeping our own stack. It
  might help on some data, but just bailing to qsort after 32 bytes is
  enough to keep stack use from exploding.

- I suspect the quicksort phase could be sped up, especially for strings.
  If you collected the next, say, eight bytes of each string in an array,
  sorted those, and only compared full strings as a tiebreaker, you could
  likely avoid following a lot of pointers and use cache better. That's a
  lot of work and a lot of code, though.

- I'm sure with a radically different approach--like with a type like this:
  type Index struct { Indices, Keys uint64 }
  you could do a bunch of other cool things.

*/

// All three radixSort functions below do a counting pass and a swapping
// pass, then recurse.  They fall back to comparison sort for small buckets
// and equal ranges, and the int sorts try to skip bits that are identical
// across the whole range being sorted.

func radixSortUint64(dataI sort.Interface, t task, sortRange func(task)) {
	data := dataI.(Uint64Interface)
	shift, a, b := uint(t.offs), t.pos, t.end
	if b-a < qSortCutoff {
		qSort(data, a, b)
		return
	}

	// use a single pass over the keys to bucket data and find min/max
	// (for skipping over bits that are always identical)
	var bucketStarts, bucketEnds [1 << radix]int
	min := data.Key(a)
	max := min
	for i := a; i < b; i++ {
		k := data.Key(i)
		bucketStarts[(k>>shift)&mask]++
		if k < min {
			min = k
		}
		if k > max {
			max = k
		}
	}

	// skip past common prefixes, bail if all keys equal
	diff := min ^ max
	if diff == 0 {
		qSortEqualKeyRange(data, a, b)
		return
	}
	if diff>>shift == 0 || diff>>(shift+radix) != 0 {
		// find highest 1 bit in diff
		log2diff := 0
		for diff != 0 {
			log2diff++
			diff >>= 1
		}
		nextShift := log2diff - radix
		if nextShift < 0 {
			nextShift = 0
		}
		sortRange(task{nextShift, a, b})
		return
	}

	pos := a
	for i, c := range bucketStarts {
		bucketStarts[i] = pos
		pos += c
		bucketEnds[i] = pos
	}

	for curBucket, bucketEnd := range bucketEnds {
		i := bucketStarts[curBucket]
		for i < bucketEnd {
			destBucket := (data.Key(i) >> shift) & mask
			if destBucket == uint64(curBucket) {
				i++
				bucketStarts[destBucket]++
				continue
			}
			data.Swap(i, bucketStarts[destBucket])
			bucketStarts[destBucket]++
		}
	}

	if shift == 0 {
		pos = a
		for _, end := range bucketEnds {
			if end > pos+1 {
				qSortEqualKeyRange(data, pos, end)
			}
			pos = end
		}
		return
	}

	nextShift := shift - radix
	if shift < radix {
		nextShift = 0
	}
	pos = a
	for _, end := range bucketEnds {
		if end > pos+1 {
			sortRange(task{int(nextShift), pos, end})
		}
		pos = end
	}
}

func radixSortInt64(dataI sort.Interface, t task, sortRange func(task)) {
	data := dataI.(Int64Interface)
	shift, a, b := uint(t.offs), t.pos, t.end
	if b-a < qSortCutoff {
		qSort(data, a, b)
		return
	}

	// use a single pass over the keys to bucket data and find min/max
	// (for skipping over bits that are always identical)
	var bucketStarts, bucketEnds [1 << radix]int
	min := int64Key(data.Key(a))
	max := min
	for i := a; i < b; i++ {
		k := int64Key(data.Key(i))
		bucketStarts[(k>>shift)&mask]++
		if k < min {
			min = k
		}
		if k > max {
			max = k
		}
	}

	// skip past common prefixes, bail if all keys equal
	diff := min ^ max
	if diff == 0 {
		qSortEqualKeyRange(data, a, b)
		return
	}
	if diff>>shift == 0 || diff>>(shift+radix) != 0 {
		// find highest 1 bit in diff
		log2diff := 0
		for diff != 0 {
			log2diff++
			diff >>= 1
		}
		nextShift := log2diff - radix
		if nextShift < 0 {
			nextShift = 0
		}
		sortRange(task{nextShift, a, b})
		return
	}

	pos := a
	for i, c := range bucketStarts {
		bucketStarts[i] = pos
		pos += c
		bucketEnds[i] = pos
	}

	for curBucket, bucketEnd := range bucketEnds {
		i := bucketStarts[curBucket]
		for i < bucketEnd {
			destBucket := (int64Key(data.Key(i)) >> shift) & mask
			if destBucket == uint64(curBucket) {
				i++
				bucketStarts[destBucket]++
				continue
			}
			data.Swap(i, bucketStarts[destBucket])
			bucketStarts[destBucket]++
		}
	}

	if shift == 0 {
		// each bucket is a unique key
		pos = a
		for _, end := range bucketEnds {
			if end > pos+1 {
				qSortEqualKeyRange(data, pos, end)
			}
			pos = end
		}
		return
	}

	nextShift := shift - radix
	if shift < radix {
		nextShift = 0
	}
	pos = a
	for _, end := range bucketEnds {
		if end > pos+1 {
			sortRange(task{int(nextShift), pos, end})
		}
		pos = end
	}
}

func radixSortString(dataI sort.Interface, t task, sortRange func(task)) {
	data := dataI.(StringInterface)
	offset, a, b := t.offs, t.pos, t.end
	if offset < 0 {
		// in a parallel quicksort of items w/long common key prefix
		quickSortWorker(data, t, sortRange)
		return
	}
	if b-a < qSortCutoff {
		qSort(data, a, b)
		return
	}
	if offset == maxRadixDepth {
		qSortPar(data, t, sortRange)
		return
	}

	// swap too-short strings to start and count bucket sizes
	bucketStarts, bucketEnds := [256]int{}, [256]int{}
	aInitial := a
	for i := a; i < b; i++ {
		k := data.Key(i)
		if len(k) <= offset {
			// swap too-short strings to start
			data.Swap(a, i)
			a++
			continue
		}
		bucketStarts[k[offset]]++
	}
	if a > aInitial+1 {
		qSortEqualKeyRange(data, aInitial, a)
	}

	pos := a
	for i, c := range bucketStarts {
		bucketStarts[i] = pos
		pos += c
		bucketEnds[i] = pos
		if bucketStarts[i] == a && bucketEnds[i] == b {
			// everything was in the same bucket
			sortRange(task{offset + 1, a, b})
			return
		}
	}

	i := a
	for curBucket, bucketEnd := range bucketEnds {
		start := i
		i = bucketStarts[curBucket]
		for i < bucketEnd {
			destBucket := data.Key(i)[offset]
			if destBucket == byte(curBucket) {
				i++
				bucketStarts[destBucket]++
				continue
			}
			data.Swap(i, bucketStarts[destBucket])
			bucketStarts[destBucket]++
		}
		if i > start+1 {
			sortRange(task{offset + 1, start, i})
		}
	}
}

func radixSortBytes(dataI sort.Interface, t task, sortRange func(task)) {
	data := dataI.(BytesInterface)
	offset, a, b := t.offs, t.pos, t.end
	if offset < 0 {
		// in a parallel quicksort of items w/long common key prefix
		quickSortWorker(data, t, sortRange)
		return
	}
	if b-a < qSortCutoff {
		qSort(data, a, b)
		return
	}
	if offset == maxRadixDepth {
		qSortPar(data, t, sortRange)
		return
	}

	// swap too-short strings to start and count bucket sizes
	bucketStarts, bucketEnds := [256]int{}, [256]int{}
	aInitial := a
	for i := a; i < b; i++ {
		k := data.Key(i)
		if len(k) <= offset {
			// swap too-short strings to start
			data.Swap(a, i)
			a++
			continue
		}
		bucketStarts[k[offset]]++
	}
	if a > aInitial+1 {
		qSortEqualKeyRange(data, aInitial, a)
	}

	pos := a
	for i, c := range bucketStarts {
		bucketStarts[i] = pos
		pos += c
		bucketEnds[i] = pos
		if bucketStarts[i] == a && bucketEnds[i] == b {
			// everything was in the same bucket
			sortRange(task{offset + 1, a, b})
			return
		}
	}

	i := a
	for curBucket, bucketEnd := range bucketEnds {
		start := i
		i = bucketStarts[curBucket]
		for i < bucketEnd {
			destBucket := data.Key(i)[offset]
			if destBucket == byte(curBucket) {
				i++
				bucketStarts[destBucket]++
				continue
			}
			data.Swap(i, bucketStarts[destBucket])
			bucketStarts[destBucket]++
		}
		if i > start+1 {
			sortRange(task{offset + 1, start, i})
		}
	}
}

// qSortEqualKeyRange qSorts data[a:b] if it is not already sorted
func qSortEqualKeyRange(data sort.Interface, a, b int) {
	for i := a; i < b-1; i++ {
		if data.Less(i+1, i) {
			qSort(data, a, b)
			return
		}
	}
	return
}