前端之家收集整理的这篇文章主要介绍了
Swift 几种排序实现,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import UIKit
var str = "Hello,playground"
var arry = [12,32,12,43,54,23,2,1,65,123,3]
//插入排序
for index in 1..<arry.count {
var key = arry[index]
var i = index - 1
while (i >= 0 && arry[i] > key) {
arry[i+1] = arry[i]
i = i - 1
}
arry[i+1] = key
}
print(arry)
arry = [12,3]
//选择排序
for i in 0..<arry.count {
for j in i+1..<arry.count
{
if (arry[i] >= arry[j]) {
var temp = arry[j]
arry[j] = arry[i]
arry[i] = temp
}
}
}
print(arry)var arry = [12,3]
//分治法
func merge (p:Int,q:Int,r:Int) -> Array<Int> {
print("A",arry,"p",p,"q",q,"r",r)
//
let n1:Int = q - p+1
print(n1)
let n2:Int = r - q
print(n2)
var L = [Int](repeating: 1000,count: n1+1)
var R = [Int](repeating: 1000,count: n2+1)
for i in 0..<n1 {
L[i] = arry[p+i]
}
for j in 0..<n2 {
R[j] = arry[q+j+1]
}
print("L",L,"R",R)
var i = 0
var j = 0
for k in p...r{
if (L[i]<=R[j])
{
arry[k] = L[i]
i = i + 1
}else
{
arry[k] = R[j]
j = j + 1
}
}
return arry
}
func merge_sort (arry:[Int],p:Int,r:Int) {
if (p < r) {
let q = (p+r)/2
print(p,r)
merge_sort(arry: arry,p: p,r: q)
merge_sort(arry: arry,p: q+1,r: r)
let a = merge(p: p,q: q,r: r)
print(a)
}
}
merge_sort(arry: arry,p: 0,r: 12)
原文链接:https://www.f2er.com/swift/322594.html