| 1 |
// Copyright 2014-5 Randall Farmer. All rights reserved. |
| 2 |
|
| 3 |
// Use of this source code is governed by a BSD-style license that can be |
| 4 |
// found in the LICENSE file. |
| 5 |
|
| 6 |
package sorts |
| 7 |
|
| 8 |
import ( |
| 9 |
"bytes" |
| 10 |
"sort" |
| 11 |
) |
| 12 |
|
| 13 |
const radix = 8 |
| 14 |
const mask = (1 << radix) - 1 |
| 15 |
|
| 16 |
// qSortCutoff is when we bail out to a quicksort. It's changed to 1 for |
| 17 |
// certain tests so we can more easily exercise the radix sorting. This was |
| 18 |
// around the break-even point in some sloppy tests. |
| 19 |
var qSortCutoff = 1 << 7 |
| 20 |
|
| 21 |
const keyPanicMessage = "sort failed: Key and Less aren't consistent with each other" |
| 22 |
const keyUint64Help = " (for float data, sortutil Key functions may help resolve this)" |
| 23 |
const panicMessage = "sort failed: could be a data race, a bug in package sorts, or a subtle bug in the interface implementation" |
| 24 |
|
| 25 |
// maxRadixDepth limits how deeply the radix part of string sorts can |
| 26 |
// recurse before we bail to quicksort. Each recursion uses 2KB stack. |
| 27 |
const maxRadixDepth = 32 |
| 28 |
|
| 29 |
// task describes a range of data to be sorted and additional |
| 30 |
// information the sorter needs: bitshift in a numeric sort, byte offset in |
| 31 |
// a string sort, or maximum depth (expressed as -maxDepth-1) for a |
| 32 |
// quicksort. |
| 33 |
type task struct{ offs, pos, end int } |
| 34 |
|
| 35 |
// ByUint64 sorts data by a uint64 key. |
| 36 |
func ByUint64(data Uint64Interface) { |
| 37 |
l := data.Len() |
| 38 |
if l < qSortCutoff { |
| 39 |
qSort(data, 0, l) |
| 40 |
return |
| 41 |
} |
| 42 |
|
| 43 |
shift := guessIntShift(data, l) |
| 44 |
parallelSort(data, radixSortUint64, task{offs: int(shift), end: l}) |
| 45 |
|
| 46 |
// check results if we radix sorted! |
| 47 |
for i := 1; i < l; i++ { |
| 48 |
if data.Less(i, i-1) { |
| 49 |
if data.Key(i) > data.Key(i-1) { |
| 50 |
panic(keyPanicMessage + keyUint64Help) |
| 51 |
} |
| 52 |
panic(panicMessage) |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
// int64Key generates a uint64 from an int64 |
| 58 |
func int64Key(i int64) uint64 { return uint64(i) ^ 1<<63 } |
| 59 |
|
| 60 |
// intwrapper tunrs an Int64Interface into a Uint64Interface for |
| 61 |
// guessIntShift |
| 62 |
type intwrapper struct{ Int64Interface } |
| 63 |
|
| 64 |
func (iw intwrapper) Key(i int) uint64 { |
| 65 |
return int64Key(iw.Int64Interface.Key(i)) |
| 66 |
} |
| 67 |
|
| 68 |
// ByInt64 sorts data by an int64 key. |
| 69 |
func ByInt64(data Int64Interface) { |
| 70 |
l := data.Len() |
| 71 |
if l < qSortCutoff { |
| 72 |
qSort(data, 0, l) |
| 73 |
return |
| 74 |
} |
| 75 |
|
| 76 |
shift := guessIntShift(intwrapper{data}, l) |
| 77 |
parallelSort(data, radixSortInt64, task{offs: int(shift), end: l}) |
| 78 |
|
| 79 |
// check results! |
| 80 |
for i := 1; i < l; i++ { |
| 81 |
if data.Less(i, i-1) { |
| 82 |
if data.Key(i) > data.Key(i-1) { |
| 83 |
panic(keyPanicMessage + keyUint64Help) |
| 84 |
} |
| 85 |
panic(panicMessage) |
| 86 |
} |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
// ByString sorts data by a string key. |
| 91 |
func ByString(data StringInterface) { |
| 92 |
l := data.Len() |
| 93 |
if l < qSortCutoff { |
| 94 |
qSort(data, 0, l) |
| 95 |
return |
| 96 |
} |
| 97 |
|
| 98 |
parallelSort(data, radixSortString, task{end: l}) |
| 99 |
|
| 100 |
// check results if we radix sorted! |
| 101 |
for i := 1; i < l; i++ { |
| 102 |
if data.Less(i, i-1) { |
| 103 |
if data.Key(i) > data.Key(i-1) { |
| 104 |
panic(keyPanicMessage) |
| 105 |
} |
| 106 |
panic(panicMessage) |
| 107 |
} |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
// ByBytes sorts data by a []byte key. |
| 112 |
func ByBytes(data BytesInterface) { |
| 113 |
l := data.Len() |
| 114 |
if l < qSortCutoff { |
| 115 |
qSort(data, 0, l) |
| 116 |
return |
| 117 |
} |
| 118 |
|
| 119 |
parallelSort(data, radixSortBytes, task{end: l}) |
| 120 |
|
| 121 |
// check results if we radix sorted! |
| 122 |
for i := 1; i < l; i++ { |
| 123 |
if data.Less(i, i-1) { |
| 124 |
if bytes.Compare(data.Key(i), data.Key(i-1)) > 0 { |
| 125 |
panic(keyPanicMessage) |
| 126 |
} |
| 127 |
panic(panicMessage) |
| 128 |
} |
| 129 |
} |
| 130 |
} |
| 131 |
|
| 132 |
// guessIntShift saves a pass when the data is distributed roughly uniformly |
| 133 |
// in a small range (think shuffled indices into a small array), and rarely |
| 134 |
// hurts much otherwise: either it just returns 64-radix quickly, or it |
| 135 |
// returns too small a shift and the sort notices after one useless counting |
| 136 |
// pass. |
| 137 |
func guessIntShift(data Uint64Interface, l int) uint { |
| 138 |
step := l >> 5 |
| 139 |
if l > 1<<16 { |
| 140 |
step = l >> 8 |
| 141 |
} |
| 142 |
if step == 0 { // only for tests w/qSortCutoff lowered |
| 143 |
step = 1 |
| 144 |
} |
| 145 |
min := data.Key(l - 1) |
| 146 |
max := min |
| 147 |
for i := 0; i < l; i += step { |
| 148 |
k := data.Key(i) |
| 149 |
if k < min { |
| 150 |
min = k |
| 151 |
} |
| 152 |
if k > max { |
| 153 |
max = k |
| 154 |
} |
| 155 |
} |
| 156 |
diff := min ^ max |
| 157 |
log2diff := 0 |
| 158 |
for diff != 0 { |
| 159 |
log2diff++ |
| 160 |
diff >>= 1 |
| 161 |
} |
| 162 |
shiftGuess := log2diff - radix |
| 163 |
if shiftGuess < 0 { |
| 164 |
return 0 |
| 165 |
} |
| 166 |
return uint(shiftGuess) |
| 167 |
} |
| 168 |
|
| 169 |
/* |
| 170 |
Thanks to (and please refer to): |
| 171 |
|
| 172 |
Victor J. Duvanenko, "Parallel In-Place Radix Sort Simplified", 2011, at |
| 173 |
http://www.drdobbs.com/parallel/parallel-in-place-radix-sort-simplified/229000734 |
| 174 |
for lots of practical discussion of performance |
| 175 |
|
| 176 |
Michael Herf, "Radix Tricks", 2001, at |
| 177 |
http://stereopsis.com/radix.html |
| 178 |
for the idea for Float32Key()/Float64Key() (via Pierre Tardiman, "Radix Sort |
| 179 |
Revisited", 2000, at http://codercorner.com/RadixSortRevisited.htm) and more |
| 180 |
performance talk. |
| 181 |
|
| 182 |
A handy slide deck summarizing Robert Sedgewick and Kevin Wayne's Algorithms |
| 183 |
on string sorts: |
| 184 |
http://algs4.cs.princeton.edu/lectures/51StringSorts.pdf |
| 185 |
for a grounding in string sorts and pointer to American flag sort |
| 186 |
|
| 187 |
McIlroy, Bostic, and McIlroy, "Engineering Radix Sort", 1993 at |
| 188 |
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6990 |
| 189 |
for laying out American flag sort |
| 190 |
|
| 191 |
- We're not using American flag sort's trick of keeping our own stack. It |
| 192 |
might help on some data, but just bailing to qsort after 32 bytes is |
| 193 |
enough to keep stack use from exploding. |
| 194 |
|
| 195 |
- I suspect the quicksort phase could be sped up, especially for strings. |
| 196 |
If you collected the next, say, eight bytes of each string in an array, |
| 197 |
sorted those, and only compared full strings as a tiebreaker, you could |
| 198 |
likely avoid following a lot of pointers and use cache better. That's a |
| 199 |
lot of work and a lot of code, though. |
| 200 |
|
| 201 |
- I'm sure with a radically different approach--like with a type like this: |
| 202 |
type Index struct { Indices, Keys uint64 } |
| 203 |
you could do a bunch of other cool things. |
| 204 |
|
| 205 |
*/ |
| 206 |
|
| 207 |
// All three radixSort functions below do a counting pass and a swapping |
| 208 |
// pass, then recurse. They fall back to comparison sort for small buckets |
| 209 |
// and equal ranges, and the int sorts try to skip bits that are identical |
| 210 |
// across the whole range being sorted. |
| 211 |
|
| 212 |
func radixSortUint64(dataI sort.Interface, t task, sortRange func(task)) { |
| 213 |
data := dataI.(Uint64Interface) |
| 214 |
shift, a, b := uint(t.offs), t.pos, t.end |
| 215 |
if b-a < qSortCutoff { |
| 216 |
qSort(data, a, b) |
| 217 |
return |
| 218 |
} |
| 219 |
|
| 220 |
// use a single pass over the keys to bucket data and find min/max |
| 221 |
// (for skipping over bits that are always identical) |
| 222 |
var bucketStarts, bucketEnds [1 << radix]int |
| 223 |
min := data.Key(a) |
| 224 |
max := min |
| 225 |
for i := a; i < b; i++ { |
| 226 |
k := data.Key(i) |
| 227 |
bucketStarts[(k>>shift)&mask]++ |
| 228 |
if k < min { |
| 229 |
min = k |
| 230 |
} |
| 231 |
if k > max { |
| 232 |
max = k |
| 233 |
} |
| 234 |
} |
| 235 |
|
| 236 |
// skip past common prefixes, bail if all keys equal |
| 237 |
diff := min ^ max |
| 238 |
if diff == 0 { |
| 239 |
qSortEqualKeyRange(data, a, b) |
| 240 |
return |
| 241 |
} |
| 242 |
if diff>>shift == 0 || diff>>(shift+radix) != 0 { |
| 243 |
// find highest 1 bit in diff |
| 244 |
log2diff := 0 |
| 245 |
for diff != 0 { |
| 246 |
log2diff++ |
| 247 |
diff >>= 1 |
| 248 |
} |
| 249 |
nextShift := log2diff - radix |
| 250 |
if nextShift < 0 { |
| 251 |
nextShift = 0 |
| 252 |
} |
| 253 |
sortRange(task{nextShift, a, b}) |
| 254 |
return |
| 255 |
} |
| 256 |
|
| 257 |
pos := a |
| 258 |
for i, c := range bucketStarts { |
| 259 |
bucketStarts[i] = pos |
| 260 |
pos += c |
| 261 |
bucketEnds[i] = pos |
| 262 |
} |
| 263 |
|
| 264 |
for curBucket, bucketEnd := range bucketEnds { |
| 265 |
i := bucketStarts[curBucket] |
| 266 |
for i < bucketEnd { |
| 267 |
destBucket := (data.Key(i) >> shift) & mask |
| 268 |
if destBucket == uint64(curBucket) { |
| 269 |
i++ |
| 270 |
bucketStarts[destBucket]++ |
| 271 |
continue |
| 272 |
} |
| 273 |
data.Swap(i, bucketStarts[destBucket]) |
| 274 |
bucketStarts[destBucket]++ |
| 275 |
} |
| 276 |
} |
| 277 |
|
| 278 |
if shift == 0 { |
| 279 |
pos = a |
| 280 |
for _, end := range bucketEnds { |
| 281 |
if end > pos+1 { |
| 282 |
qSortEqualKeyRange(data, pos, end) |
| 283 |
} |
| 284 |
pos = end |
| 285 |
} |
| 286 |
return |
| 287 |
} |
| 288 |
|
| 289 |
nextShift := shift - radix |
| 290 |
if shift < radix { |
| 291 |
nextShift = 0 |
| 292 |
} |
| 293 |
pos = a |
| 294 |
for _, end := range bucketEnds { |
| 295 |
if end > pos+1 { |
| 296 |
sortRange(task{int(nextShift), pos, end}) |
| 297 |
} |
| 298 |
pos = end |
| 299 |
} |
| 300 |
} |
| 301 |
|
| 302 |
func radixSortInt64(dataI sort.Interface, t task, sortRange func(task)) { |
| 303 |
data := dataI.(Int64Interface) |
| 304 |
shift, a, b := uint(t.offs), t.pos, t.end |
| 305 |
if b-a < qSortCutoff { |
| 306 |
qSort(data, a, b) |
| 307 |
return |
| 308 |
} |
| 309 |
|
| 310 |
// use a single pass over the keys to bucket data and find min/max |
| 311 |
// (for skipping over bits that are always identical) |
| 312 |
var bucketStarts, bucketEnds [1 << radix]int |
| 313 |
min := int64Key(data.Key(a)) |
| 314 |
max := min |
| 315 |
for i := a; i < b; i++ { |
| 316 |
k := int64Key(data.Key(i)) |
| 317 |
bucketStarts[(k>>shift)&mask]++ |
| 318 |
if k < min { |
| 319 |
min = k |
| 320 |
} |
| 321 |
if k > max { |
| 322 |
max = k |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
// skip past common prefixes, bail if all keys equal |
| 327 |
diff := min ^ max |
| 328 |
if diff == 0 { |
| 329 |
qSortEqualKeyRange(data, a, b) |
| 330 |
return |
| 331 |
} |
| 332 |
if diff>>shift == 0 || diff>>(shift+radix) != 0 { |
| 333 |
// find highest 1 bit in diff |
| 334 |
log2diff := 0 |
| 335 |
for diff != 0 { |
| 336 |
log2diff++ |
| 337 |
diff >>= 1 |
| 338 |
} |
| 339 |
nextShift := log2diff - radix |
| 340 |
if nextShift < 0 { |
| 341 |
nextShift = 0 |
| 342 |
} |
| 343 |
sortRange(task{nextShift, a, b}) |
| 344 |
return |
| 345 |
} |
| 346 |
|
| 347 |
pos := a |
| 348 |
for i, c := range bucketStarts { |
| 349 |
bucketStarts[i] = pos |
| 350 |
pos += c |
| 351 |
bucketEnds[i] = pos |
| 352 |
} |
| 353 |
|
| 354 |
for curBucket, bucketEnd := range bucketEnds { |
| 355 |
i := bucketStarts[curBucket] |
| 356 |
for i < bucketEnd { |
| 357 |
destBucket := (int64Key(data.Key(i)) >> shift) & mask |
| 358 |
if destBucket == uint64(curBucket) { |
| 359 |
i++ |
| 360 |
bucketStarts[destBucket]++ |
| 361 |
continue |
| 362 |
} |
| 363 |
data.Swap(i, bucketStarts[destBucket]) |
| 364 |
bucketStarts[destBucket]++ |
| 365 |
} |
| 366 |
} |
| 367 |
|
| 368 |
if shift == 0 { |
| 369 |
// each bucket is a unique key |
| 370 |
pos = a |
| 371 |
for _, end := range bucketEnds { |
| 372 |
if end > pos+1 { |
| 373 |
qSortEqualKeyRange(data, pos, end) |
| 374 |
} |
| 375 |
pos = end |
| 376 |
} |
| 377 |
return |
| 378 |
} |
| 379 |
|
| 380 |
nextShift := shift - radix |
| 381 |
if shift < radix { |
| 382 |
nextShift = 0 |
| 383 |
} |
| 384 |
pos = a |
| 385 |
for _, end := range bucketEnds { |
| 386 |
if end > pos+1 { |
| 387 |
sortRange(task{int(nextShift), pos, end}) |
| 388 |
} |
| 389 |
pos = end |
| 390 |
} |
| 391 |
} |
| 392 |
|
| 393 |
func radixSortString(dataI sort.Interface, t task, sortRange func(task)) { |
| 394 |
data := dataI.(StringInterface) |
| 395 |
offset, a, b := t.offs, t.pos, t.end |
| 396 |
if offset < 0 { |
| 397 |
// in a parallel quicksort of items w/long common key prefix |
| 398 |
quickSortWorker(data, t, sortRange) |
| 399 |
return |
| 400 |
} |
| 401 |
if b-a < qSortCutoff { |
| 402 |
qSort(data, a, b) |
| 403 |
return |
| 404 |
} |
| 405 |
if offset == maxRadixDepth { |
| 406 |
qSortPar(data, t, sortRange) |
| 407 |
return |
| 408 |
} |
| 409 |
|
| 410 |
// swap too-short strings to start and count bucket sizes |
| 411 |
bucketStarts, bucketEnds := [256]int{}, [256]int{} |
| 412 |
aInitial := a |
| 413 |
for i := a; i < b; i++ { |
| 414 |
k := data.Key(i) |
| 415 |
if len(k) <= offset { |
| 416 |
// swap too-short strings to start |
| 417 |
data.Swap(a, i) |
| 418 |
a++ |
| 419 |
continue |
| 420 |
} |
| 421 |
bucketStarts[k[offset]]++ |
| 422 |
} |
| 423 |
if a > aInitial+1 { |
| 424 |
qSortEqualKeyRange(data, aInitial, a) |
| 425 |
} |
| 426 |
|
| 427 |
pos := a |
| 428 |
for i, c := range bucketStarts { |
| 429 |
bucketStarts[i] = pos |
| 430 |
pos += c |
| 431 |
bucketEnds[i] = pos |
| 432 |
if bucketStarts[i] == a && bucketEnds[i] == b { |
| 433 |
// everything was in the same bucket |
| 434 |
sortRange(task{offset + 1, a, b}) |
| 435 |
return |
| 436 |
} |
| 437 |
} |
| 438 |
|
| 439 |
i := a |
| 440 |
for curBucket, bucketEnd := range bucketEnds { |
| 441 |
start := i |
| 442 |
i = bucketStarts[curBucket] |
| 443 |
for i < bucketEnd { |
| 444 |
destBucket := data.Key(i)[offset] |
| 445 |
if destBucket == byte(curBucket) { |
| 446 |
i++ |
| 447 |
bucketStarts[destBucket]++ |
| 448 |
continue |
| 449 |
} |
| 450 |
data.Swap(i, bucketStarts[destBucket]) |
| 451 |
bucketStarts[destBucket]++ |
| 452 |
} |
| 453 |
if i > start+1 { |
| 454 |
sortRange(task{offset + 1, start, i}) |
| 455 |
} |
| 456 |
} |
| 457 |
} |
| 458 |
|
| 459 |
func radixSortBytes(dataI sort.Interface, t task, sortRange func(task)) { |
| 460 |
data := dataI.(BytesInterface) |
| 461 |
offset, a, b := t.offs, t.pos, t.end |
| 462 |
if offset < 0 { |
| 463 |
// in a parallel quicksort of items w/long common key prefix |
| 464 |
quickSortWorker(data, t, sortRange) |
| 465 |
return |
| 466 |
} |
| 467 |
if b-a < qSortCutoff { |
| 468 |
qSort(data, a, b) |
| 469 |
return |
| 470 |
} |
| 471 |
if offset == maxRadixDepth { |
| 472 |
qSortPar(data, t, sortRange) |
| 473 |
return |
| 474 |
} |
| 475 |
|
| 476 |
// swap too-short strings to start and count bucket sizes |
| 477 |
bucketStarts, bucketEnds := [256]int{}, [256]int{} |
| 478 |
aInitial := a |
| 479 |
for i := a; i < b; i++ { |
| 480 |
k := data.Key(i) |
| 481 |
if len(k) <= offset { |
| 482 |
// swap too-short strings to start |
| 483 |
data.Swap(a, i) |
| 484 |
a++ |
| 485 |
continue |
| 486 |
} |
| 487 |
bucketStarts[k[offset]]++ |
| 488 |
} |
| 489 |
if a > aInitial+1 { |
| 490 |
qSortEqualKeyRange(data, aInitial, a) |
| 491 |
} |
| 492 |
|
| 493 |
pos := a |
| 494 |
for i, c := range bucketStarts { |
| 495 |
bucketStarts[i] = pos |
| 496 |
pos += c |
| 497 |
bucketEnds[i] = pos |
| 498 |
if bucketStarts[i] == a && bucketEnds[i] == b { |
| 499 |
// everything was in the same bucket |
| 500 |
sortRange(task{offset + 1, a, b}) |
| 501 |
return |
| 502 |
} |
| 503 |
} |
| 504 |
|
| 505 |
i := a |
| 506 |
for curBucket, bucketEnd := range bucketEnds { |
| 507 |
start := i |
| 508 |
i = bucketStarts[curBucket] |
| 509 |
for i < bucketEnd { |
| 510 |
destBucket := data.Key(i)[offset] |
| 511 |
if destBucket == byte(curBucket) { |
| 512 |
i++ |
| 513 |
bucketStarts[destBucket]++ |
| 514 |
continue |
| 515 |
} |
| 516 |
data.Swap(i, bucketStarts[destBucket]) |
| 517 |
bucketStarts[destBucket]++ |
| 518 |
} |
| 519 |
if i > start+1 { |
| 520 |
sortRange(task{offset + 1, start, i}) |
| 521 |
} |
| 522 |
} |
| 523 |
} |
| 524 |
|
| 525 |
// qSortEqualKeyRange qSorts data[a:b] if it is not already sorted |
| 526 |
func qSortEqualKeyRange(data sort.Interface, a, b int) { |
| 527 |
for i := a; i < b-1; i++ { |
| 528 |
if data.Less(i+1, i) { |
| 529 |
qSort(data, a, b) |
| 530 |
return |
| 531 |
} |
| 532 |
} |
| 533 |
return |
| 534 |
} |