cubegao

Swift.冒泡排序

2015-04-15

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import Foundation

class BubbleSortSolution {
func sort(_ n: [Int]) -> [Int] {

var nums = n

for i in 0..<n.count {

for j in 0..<n.count-i-1 {
if nums[j] > nums[j+1] {
let temp = nums[j+1]
nums[j+1] = nums[j]
nums[j] = temp
}
}
}

return nums
}

}

算法思想:冒泡排序的基本思想是,对相邻的元素进行两两比较,顺序相反则进行交换,这样,每一趟会将最小或最大的元素“浮”到顶端,最终达到完全有序。

github地址:https://github.com/cubegao/LeetCode

Tags: 算法

扫描二维码,分享此文章