funcinsertionSort(array: [Int]) -> [Int]{ var sortedArray = [Int]() //将第一个加入已排序 sortedArray.append(array[0]) if array.count > 1 { for index in1...array.count - 1 { let number = array[index] //反向遍历找到要插入到已排序的数组中下标 for (sortIndex, sortNumber) in sortedArray.enumerated().reversed() { if sortNumber <= number { sortedArray.insert(number, at: sortIndex + 1) break } } } } for number in sortedArray { print(number) } return sortedArray }
funcinsertionSort2(array: inout [Int]) -> [Int] { letcount = array.count ifcount > 1 { for i in1..<count { let temp = array[i] var index = i while index >= 1 && array[index-1] > temp { array[index] = array[index-1] index -= 1 } array[index] = temp } } print(array) return array }