Skip to content

Commit 6f5d763

Browse files
Merge pull request #68 from AllanWell/master
sort of Swift
2 parents 4410a62 + 640a632 commit 6f5d763

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

swift/11_sorts/Sorts.swift

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import Foundation
2+
3+
/// 冒泡排序
4+
///
5+
/// - Parameter elements: 数组
6+
/// - Returns: 返回值
7+
public func bubbleSort<T>(_ elements: [T]) ->[T] where T: Comparable {
8+
var array = elements
9+
guard array.count > 1 else {
10+
return array
11+
}
12+
for i in 0..<array.count {
13+
// 提前退出标志位
14+
var flag = false
15+
for j in 0..<array.count - i - 1 {
16+
if array[j] > array[j+1] {
17+
array.swapAt(j+1, j)
18+
// 此次冒泡有数据交换
19+
flag = true
20+
}
21+
}
22+
if (!flag) {
23+
break
24+
}
25+
}
26+
return array
27+
}
28+
29+
30+
/// 插入排序
31+
///
32+
/// - Parameter elements: 数组
33+
/// - Returns: 返回值
34+
public func insertionSort<T>(_ elements: [T]) -> [T] where T: Comparable {
35+
var array = elements
36+
guard array.count > 1 else {
37+
return array
38+
}
39+
for i in 1..<array.count {
40+
let value = array[i]
41+
var j = i - 1;
42+
// 查找要插入的位置并移动数据
43+
for p in (0...j).reversed() {
44+
j = p
45+
if array[p] > value {
46+
array[p+1] = array[p]
47+
} else {
48+
break
49+
}
50+
}
51+
array[j+1] = value
52+
}
53+
return array
54+
}
55+
56+
57+
/// 选择排序
58+
///
59+
/// - Parameter elements: 数组
60+
/// - Returns: 返回值
61+
public func selectionSort<T>(_ elements: [T]) -> [T] where T: Comparable {
62+
var array = elements
63+
guard array.count > 1 else {
64+
return array
65+
}
66+
for i in 0..<array.count {
67+
// 查找最小值
68+
var minIndex = i
69+
var minValue = array[i]
70+
for j in i..<array.count {
71+
if array[j] < minValue {
72+
minValue = array[j]
73+
minIndex = j
74+
}
75+
}
76+
// 交换
77+
array.swapAt(i, minIndex)
78+
}
79+
return array
80+
}
81+

0 commit comments

Comments
 (0)