swift快速排序
struct QuickSort { static func sort(arr: inout [Int]) { sort(arr: &arr, l: 0, r: arr.count-1) } static func sort(arr: inout [Int], l: Int, r: Int) { if l >= r { return } let p = partition(arr: &arr, l: l, r: r) sort(arr: &arr, l: l, r: p-1) sort(arr: &arr, l: p+1, r: r) } static func partition(arr: inout [Int], l: Int, r: Int) -> Int { var j = l for index in l+1...r { if arr[index] < arr[l] { j += 1 let value = arr[index] arr[index] = arr[j] arr[j] = value } } let l_value = arr[l] arr[l] = arr[j] arr[j] = l_value return j } }
bobo老师,这是我用swift实现的快速排序。但是我在测试性能的时候发现时间会很久。以下为测试代码:
var arr = [Int]() for _ in 0...1000000 { arr.append(Int.random(in: 0...1000000)) } let date = Date() QuickSort.sort(arr: &arr) // arr.sort(by: <) let date1 = Date() print(date1.timeIntervalSince1970-date.timeIntervalSince1970)
时间差大约在20s, 即使用sort排序,也会是10s的时间。
为什么和老师视频中差的这么多呢?