@@ -40,7 +40,7 @@ Now, all we must do is take the value at index `a.count - k`:
4040a[a.count - k] = a[8 - 4 ] = a[4 ] = 9
4141```
4242
43- Of course, if you were looking for the k-th * smallest* element, you'd use ` a[k] ` .
43+ Of course, if you were looking for the k-th * smallest* element, you'd use ` a[k-1 ] ` .
4444
4545## A faster solution
4646
@@ -84,29 +84,29 @@ The index of pivot `9` is 4, and that's exactly the *k* we're looking for. We're
8484The following function implements these ideas:
8585
8686``` swift
87- public func randomizedSelect <T : Comparable >(array : [T], order k : Int ) -> T {
87+ public func randomizedSelect <T : Comparable >(_ array : [T], order k : Int ) -> T {
8888 var a = array
8989
90- func randomPivot <T : Comparable >(inout a : [T], _ low : Int , _ high : Int ) -> T {
90+ func randomPivot <T : Comparable >(_ a : inout [T], _ low : Int , _ high : Int ) -> T {
9191 let pivotIndex = random (min : low, max : high)
92- swap ( & a, pivotIndex, high)
92+ a. swapAt ( pivotIndex, high)
9393 return a[high]
9494 }
9595
96- func randomizedPartition <T : Comparable >(inout a : [T], _ low : Int , _ high : Int ) -> Int {
96+ func randomizedPartition <T : Comparable >(_ a : inout [T], _ low : Int , _ high : Int ) -> Int {
9797 let pivot = randomPivot (& a, low, high)
9898 var i = low
9999 for j in low..< high {
100100 if a[j] <= pivot {
101- swap ( & a, i, j)
101+ a. swapAt ( i, j)
102102 i += 1
103103 }
104104 }
105- swap ( & a, i, high)
105+ a. swapAt ( i, high)
106106 return i
107107 }
108108
109- func randomizedSelect <T : Comparable >(inout a : [T], _ low : Int , _ high : Int , _ k : Int ) -> T {
109+ func randomizedSelect <T : Comparable >(_ a : inout [T], _ low : Int , _ high : Int , _ k : Int ) -> T {
110110 if low < high {
111111 let p = randomizedPartition (& a, low, high)
112112 if k == p {
0 commit comments