Advertisement
Guest User

Untitled

a guest
May 24th, 2015
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. //: Playground - noun: a place where people can play
  2.  
  3. import UIKit
  4.  
  5. var str = "Hello, playground"
  6.  
  7. func max(a:[Int], n:Int) -> Int
  8. {
  9. var m = a[0]
  10. for i in 0...(n - 1) {
  11. if (a[i] > m) {
  12. m = a[i]
  13. }
  14. }
  15. return m
  16. }
  17.  
  18. // modified countsort to sort by the frequecy of the least significant bit
  19. // count[fi]++ where fi = (input[i] / x) % 10
  20. func countSort(inout a:[Int], n:Int, x:Int)
  21. {
  22. // output array and frequency array 10 is used to represent digits 0-9
  23. var outp = [Int](count: n, repeatedValue: 0)
  24. var freq = [Int](count: 10, repeatedValue: 0)
  25.  
  26.  
  27. // build a frequency list freq by counting the least significant digit represented by (input[i] / x) % 10
  28. for i in 0...(n - 1) {
  29.  
  30. var fi = (a[i] / x) % 10
  31. freq[fi]++
  32. }
  33.  
  34. // Change count[i] so that count[i] now contains actual position of
  35. // this value in output array
  36. for i in 1...(freq.count - 1) {
  37. freq[i] += freq[i - 1]
  38. }
  39.  
  40.  
  41. // build output of the list calculating the freqency table index (fi) where i -> n...0
  42. for (var i = (n - 1); i >= 0; i--) {
  43.  
  44. // calculate the position of the least significant digit index in the frequency table
  45. var fi = (a[i] / x) % 10
  46.  
  47. outp[freq[fi] - 1] = a[i]
  48. freq[fi]--
  49. }
  50.  
  51. // copy temp array to new array
  52. for i in 0...(n - 1) {
  53. a[i] = outp[i]
  54. }
  55. }
  56.  
  57. func radixSort(inout a:[Int], n:Int)
  58. {
  59. var m = max(a, n)
  60.  
  61. // repeatadly count sort on the least significant digit on each pass
  62. for var x = 1; m/x > 0; x *= 10 {
  63. countSort(&a, n, x)
  64. }
  65. }
  66.  
  67. var a = [170,45, 4, 170, 45, 75, 90, 802, 24, 2, 66, 1000]
  68. radixSort(&a, a.count)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement