两个有序数组合并成一个有序数组

extension ViewController {
    func mergeOrderArray(With firstAry: Array,
                         secondAry: Array) -> Array {
        
        var FirstAry = firstAry
        var SecondAry = secondAry
        if FirstAry.isEmpty &&
            SecondAry.isEmpty{
            return []
        }
        
        if FirstAry.isEmpty {
            return SecondAry
        }
        
        if secondAry.isEmpty {
            return FirstAry
        }
        
        var endAry = [String]()
        
        while true {
            if Int(FirstAry.first!) ?? 0 < Int(SecondAry.first!) ?? 0 {
                endAry.append(FirstAry.first!)
                FirstAry.removeFirst()
            } else {
                endAry.append(SecondAry.first!)
                SecondAry.removeFirst()
            }
            
            if FirstAry.isEmpty {
                endAry.append(contentsOf: SecondAry)
                break
            }
            
            if SecondAry.isEmpty {
                endAry.append(contentsOf: FirstAry)
                break
            }
        }
    
        return endAry
    }
}

print(mergeOrderArray(With: ["1","3","5","7","9"],
                              secondAry: ["1","2","17","20","35"]))

打印结果

["1", "1", "2", "3", "5", "7", "9", "17", "20", "35"]

你可能感兴趣的:(两个有序数组合并成一个有序数组)