Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. class List<T : Comparable> {
  2. init(_ value: T) { self.value = value }
  3. init(_ value: T, _ next: List<T>?) {
  4. self.value = value
  5. self.next = next
  6. }
  7.  
  8. var value: T
  9. var next: List<T>? = nil
  10.  
  11. func length() -> Int {
  12. func inner(_ list: List<T>?, _ count: Int) -> Int {
  13. guard let list = list else { return count }
  14. return inner(list.next, count + 1)
  15. }
  16.  
  17. return inner(self, 0)
  18. }
  19. }
  20.  
  21. func cons<T>(_ head: List<T>, _ tail: List<T>?) -> List<T> {
  22. assert(head.next == nil)
  23. head.next = tail
  24. return head
  25. }
  26.  
  27. func merge<T>(_ fst: List<T>?, _ snd: List<T>?) -> List<T>? {
  28. guard let fst = fst else { return snd }
  29. guard let snd = snd else { return fst }
  30.  
  31. if fst.value < snd.value {
  32. return cons(List(fst.value), merge(fst.next, snd))
  33. } else {
  34. return cons(List(snd.value), merge(fst, snd.next))
  35. }
  36. }
  37.  
  38. func drop<T>(_ list: List<T>?, _ count: Int) -> List<T>? {
  39. guard let list = list else { return nil }
  40. guard count != 0 else { return list }
  41.  
  42. return drop(list.next, count - 1)
  43. }
  44.  
  45. func take<T>(_ list: List<T>?, _ count: Int) -> List<T>? {
  46. guard let list = list, count != 0 else { return nil }
  47.  
  48. func inner(_ oldList: List<T>?, _ count: Int, _ listAndLast: (List<T>, List<T>)) -> List<T> {
  49. let (list, last) = listAndLast
  50.  
  51. guard let oldList = oldList, count != 0 else { return list }
  52.  
  53. let next = List(oldList.value)
  54. last.next = next
  55.  
  56. return inner(oldList.next, count - 1, (list, next))
  57. }
  58.  
  59. let last = List(list.value)
  60. return inner(list.next, count - 1, (last, last))
  61. }
  62.  
  63. func sort<T>(_ list: List<T>?) -> List<T>? {
  64. guard let list = list else { return nil }
  65. let length = list.length()
  66. if length == 1 { return list }
  67.  
  68. let fst = take(list, length / 2)
  69. let snd = drop(list, length / 2)
  70.  
  71. return merge(sort(fst), sort(snd))
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement