搜索
您的当前位置:首页正文

iOS程序员也要学点算法吧-简单排序之选择排序

来源:二三娱乐
1.gif

在大数据量的时候交换次数显得尤为明显

1.gif

代码如图

Paste_Image.png
//:MARK - 2 选择排序

 func selectSort<T:Comparable>( aArr:[T]) -> [T] {
    var arr = aArr
    var minIndex = 0 // 记录每次遍历的最小值
    for outerIndex in 0..<arr.count {
        minIndex = outerIndex
        for innerIndex in (outerIndex + 1)..<arr.count {
            if arr[minIndex] > arr[innerIndex] {
                    minIndex = innerIndex // 判断最小值,充值选择的标记
             }
     //            在每次外层遍历之后再交换

if minIndex != outerIndex {
let t = arr[outerIndex]
arr[outerIndex] = arr[minIndex]
arr[minIndex] = t
}
}
}

          return arr
  }

    print(selectSort([9,8,7,6,5,4,3,2,1,0]))
Top