Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. package object radixSort {
  2. /**
  3. * Least-significant-digit-first radix sort for integer arrays.
  4. * Sorts the argument array in ascending order.
  5. * Assumes that all the integers are non-negative.
  6. * Interpret 'digit' as 'byte' (8 bits) here and use bit-level operations
  7. * such as shifting (>> and <<) and masking (&) to extract 'digits'.
  8. */
  9. def byteToInt(n: Int, shiftRight: Int): Int = {
  10. (n >> shiftRight) & 0xFF
  11. }
  12.  
  13. def cumulate(a: Array[Int]): Array[Int] = {
  14. var index = 0
  15. var cumulative = 0
  16. while (index < a.length) {
  17. val t = a(index)
  18. a(index) = cumulative
  19. cumulative += t
  20. index += 1
  21. }
  22. a
  23. }
  24.  
  25. def lsdRadixSort(a: Array[Int]): Unit = {
  26. val N = a.length
  27. if(N <= 1) return
  28.  
  29. var byteSize = 8
  30. var intSize = 32
  31. var shiftBy = 0
  32.  
  33. while(shiftBy < intSize) {
  34. var count = Array.fill(256)(0)
  35. var result = Array.fill(N)(0)
  36.  
  37. var i = 0
  38. while (i < N) {
  39. count(byteToInt(a(i), shiftBy)) += 1
  40. i += 1
  41. }
  42. if (count(0) == N) return
  43. count = cumulate(count)
  44. i = 0
  45. while(i < N) {
  46. val target = byteToInt(a(i), shiftBy)
  47. result(count(target)) = a(i)
  48. count(target) = count(target) + 1
  49. i += 1
  50. }
  51. i = 0
  52. while(i < N) {
  53. a(i) = result(i)
  54. i += 1
  55. }
  56.  
  57. shiftBy += byteSize
  58. }
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement