排序之选择排序实现(swift)

前端之家收集整理的这篇文章主要介绍了排序之选择排序实现(swift)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//
//  main.swift
// 
//
//  Created by LongMa on 2020/7/4.
//  Copyright © 2020 . All rights reserved.
//

import Foundation

print("Hello,World!")

func kp(arr : [Int]) ->  Array<Int>{
    var a = arr
    let len = arr.count
    
    var indexOfMinNum,temp : Int
    for i in 0..<(len - 1) {//eg:3个数,应循环2次
        indexOfMinNum = i
        
        //无序部分,查找最小值,记录下标。
        for j in (i+1)..<(len){//eg:3个数,最大小标为2。
            if a[j] < a[indexOfMinNum] {
                indexOfMinNum = j
            }
        }
        
        //交换无序部分0位值和最小值
        if i != indexOfMinNum {
            temp = a[i]
            a[i] = a[indexOfMinNum]
            a[indexOfMinNum] = temp
        }
    }
    return a
}

let lArr = [22,6,4,5,10,11,2,1,0]
let lA = kp(arr: lArr)
print(lA)

let lArr1 = [23,8,9,3,1]
let lA1 = kp(arr: lArr1)
print(lA1)

log:

Hello,World!
[0,22]
[0,23]
Program ended with exit code: 0

猜你在找的iOS相关文章