Swift-冒泡排序

冒泡排序算是入门排序,排序原理如下:
①比较相邻的元素。如果第一个比第二个大,就交换他们两个。
②对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
针对所有的元素重复以上的步骤,除了最后一个。
③持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
通过三种方式来实现排序过程:
<pre><code>` func bubbleSort(arr:inout [Int]) {
let count:Int = arr.count
for i in 0..<count {
for j in i..<count {
if arr[i] > arr[j] {
swap(&arr[i], &arr[j])
}
}
}
}

func bubbleSort1(arr:inout [Int]) {
    let count:Int = arr.count
    for i in 0..<count {
        let max:Int = count - i - 1
        for j in 0..<max {
            if arr[j] > arr[j+1] {
                swap(&arr[j], &arr[j+1])
            }
        }
    }
}

func bubbleSort2(arr:inout [Int]) {
    let count:Int = arr.count
    for i in (0..<count).reversed() {
        for j in 0..<i {
            if arr[j] > arr[j+1] {
                swap(&arr[j], &arr[j+1])
            }
        }
    }
}`</code></pre>

测试代码:
<pre><code>` func bubbleSort() {
var bubbleArr:[Int] = [1,3,7,2,4,1,0]
let bubbleSort:BubbleSort = BubbleSort()
bubbleSort.bubbleSort(arr: &bubbleArr)
print("FlyElephant-冒泡排序之后的数组---(bubbleArr)")

    bubbleArr = [1,3,7,2,4,1,0]
    bubbleSort.bubbleSort1(arr: &bubbleArr)
    print("FlyElephant-冒泡排序之后的数组---\(bubbleArr)")
    
    bubbleArr = [1,3,7,2,4,1,0]
    bubbleSort.bubbleSort2(arr: &bubbleArr)
    print("FlyElephant-冒泡排序之后的数组---\(bubbleArr)")
}`</code></pre>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容