Swift 归并排序

前端之家收集整理的这篇文章主要介绍了Swift 归并排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

用Swift写的一个归并排序算法(递归法)

func Merge(sourceArray: NSMutableArray,tempArray: NSMutableArray,startIndex: Int,midIndex: Int,endIndex: Int) {
    var i = startIndex
    var j = midIndex + 1
    var k = startIndex
        
    while(i != midIndex+1 && j != endIndex+1) {
        let one = sourceArray[i] as! Int
        let two = sourceArray[j] as! Int
        if one >= two {
            tempArray.insertObject(sourceArray[j],atIndex: k)
            j += 1
            k += 1
        }else {
            tempArray.insertObject(sourceArray[i],atIndex: k)
            i += 1
            k += 1
        }
    }
    while(i != midIndex+1) {
        tempArray.insertObject(sourceArray[i],atIndex: k)
        i += 1
        k += 1
    }
    while(j != endIndex+1) {
        tempArray.insertObject(sourceArray[j],atIndex: k)
        j += 1
        k += 1
    }
        
    for i in startIndex...endIndex {
        sourceArray.replaceObjectAtIndex(i,withObject: tempArray[i])
    }
}
    
func MergeSort(sourceArray: NSMutableArray,endIndex: Int) {
    var midIndex = 0
    if startIndex < endIndex {
        midIndex = (startIndex + endIndex)/2
        MergeSort(sourceArray,tempArray: tempArray,startIndex: startIndex,endIndex: midIndex)
        MergeSort(sourceArray,startIndex: midIndex+1,endIndex: endIndex)
        Merge(sourceArray,midIndex: midIndex,endIndex: endIndex)
    }
}
从小到大排列。 原文链接:https://www.f2er.com/swift/322779.html

猜你在找的Swift相关文章