Swift3.0 选择排序

作者: Jiubao | 来源:发表于2016-07-26 00:17 被阅读18次

    选择排序
    SelectionSort.swift如下:

    //选择排序
    
    var a = [6, 5, 4, 3, 2, 1]
    
    print("array is \(a)")
    
    var i,j,min,temp: Int
    
    //遍历一遍数组
    for i in 0..<a.count-1 {
        min = i
        
        //挨个比较其他数字
        for j in i+1..<a.count {
            print("i is \(i) and j is \(j) and min is \(min) and a[min] is \(a[min])")
            
            //看当前是否真的是最小数字
            if a[min] > a[j] {
                //a[j]更小,所以更新 min
                min = j
                
                print("change \(a[min]) and \(a[i])")
                
                let temp = a[min]
                a[min] = a[i]
                a[i] = temp
            }
        }
    }
    
    //排序结束
    print("sorted array is \(a)")
    
    

    Terminal运行swift SelectionSort.swift

    array is [6, 5, 4, 3, 2, 1]
    i is 0 and j is 1 and min is 0 and a[min] is 6
    change 5 and 6
    i is 0 and j is 2 and min is 1 and a[min] is 6
    change 4 and 5
    i is 0 and j is 3 and min is 2 and a[min] is 5
    change 3 and 4
    i is 0 and j is 4 and min is 3 and a[min] is 4
    change 2 and 3
    i is 0 and j is 5 and min is 4 and a[min] is 3
    change 1 and 2
    i is 1 and j is 2 and min is 1 and a[min] is 6
    change 5 and 6
    i is 1 and j is 3 and min is 2 and a[min] is 6
    change 4 and 5
    i is 1 and j is 4 and min is 3 and a[min] is 5
    change 3 and 4
    i is 1 and j is 5 and min is 4 and a[min] is 4
    change 2 and 3
    i is 2 and j is 3 and min is 2 and a[min] is 6
    change 5 and 6
    i is 2 and j is 4 and min is 3 and a[min] is 6
    change 4 and 5
    i is 2 and j is 5 and min is 4 and a[min] is 5
    change 3 and 4
    i is 3 and j is 4 and min is 3 and a[min] is 6
    change 5 and 6
    i is 3 and j is 5 and min is 4 and a[min] is 6
    change 4 and 5
    i is 4 and j is 5 and min is 4 and a[min] is 6
    change 5 and 6
    sorted array is [1, 2, 3, 4, 5, 6]
    

    相关文章

      网友评论

        本文标题:Swift3.0 选择排序

        本文链接:https://www.haomeiwen.com/subject/avlnjttx.html