radixSortResults sorts Results by their points key using LSD radix sort. O(n) time complexity vs O(n log n) for comparison sort. The sort is stable, so equal-key items maintain original (item-index) order. For tac mode, runs of equal keys are reversed after sorting.
(a []Result, tac bool, scratch []Result)
| 349 | // The sort is stable, so equal-key items maintain original (item-index) order. |
| 350 | // For tac mode, runs of equal keys are reversed after sorting. |
| 351 | func radixSortResults(a []Result, tac bool, scratch []Result) []Result { |
| 352 | n := len(a) |
| 353 | if n < 128 { |
| 354 | if tac { |
| 355 | sort.Sort(ByRelevanceTac(a)) |
| 356 | } else { |
| 357 | sort.Sort(ByRelevance(a)) |
| 358 | } |
| 359 | return scratch[:0] |
| 360 | } |
| 361 | |
| 362 | if cap(scratch) < n { |
| 363 | scratch = make([]Result, n) |
| 364 | } |
| 365 | buf := scratch[:n] |
| 366 | src, dst := a, buf |
| 367 | scattered := 0 |
| 368 | |
| 369 | for pass := range 8 { |
| 370 | shift := uint(pass) * 8 |
| 371 | |
| 372 | var count [256]int |
| 373 | for i := range src { |
| 374 | count[byte(sortKey(&src[i])>>shift)]++ |
| 375 | } |
| 376 | |
| 377 | // Skip if all items have the same byte value at this position |
| 378 | if count[byte(sortKey(&src[0])>>shift)] == n { |
| 379 | continue |
| 380 | } |
| 381 | |
| 382 | var offset [256]int |
| 383 | for i := 1; i < 256; i++ { |
| 384 | offset[i] = offset[i-1] + count[i-1] |
| 385 | } |
| 386 | |
| 387 | for i := range src { |
| 388 | b := byte(sortKey(&src[i]) >> shift) |
| 389 | dst[offset[b]] = src[i] |
| 390 | offset[b]++ |
| 391 | } |
| 392 | |
| 393 | src, dst = dst, src |
| 394 | scattered++ |
| 395 | } |
| 396 | |
| 397 | // If odd number of scatters, data is in buf, copy back to a |
| 398 | if scattered%2 == 1 { |
| 399 | copy(a, src) |
| 400 | } |
| 401 | |
| 402 | // Handle tac: reverse runs of equal keys so equal-key items |
| 403 | // are in reverse item-index order |
| 404 | if tac { |
| 405 | i := 0 |
| 406 | for i < n { |
| 407 | ki := sortKey(&a[i]) |
| 408 | j := i + 1 |
searching dependent graphs…