Swift.归并排序

cubegao 2015-05-21 PM 460℃ 0条
import Foundation

class MergeSortSolution {
    func sort(_ n: [Int]) -> [Int] {
        
        var s = n
        sortArray(&s, 0, n.count - 1)
        return s
    }
    
    func sortArray(_ n: inout [Int],_ left: Int,_ right: Int){
        if left < right {
            let mid = (left + right)/2
            sortArray(&n, left, mid)
            sortArray(&n, mid+1, right)
            merge(&n, left, right)
        }
    }
    
    //合并left->mid和mid+1->right
    func merge(_ n: inout [Int],_ leftIn: Int,_ rightIn: Int) {
        var temp = [Int]()
        let mid = (leftIn + rightIn)/2
        var left = leftIn
        var right = mid + 1

        
        while left <= mid && right <= rightIn {
            if n[left] < n[right] {
                temp.append(n[left])
                left += 1
            }else {
                temp.append(n[right])
                right += 1
            }
        }
        
        while left <= mid {
            temp.append(n[left])
            left += 1
        }
        
        while right <= rightIn {
            temp.append(n[right])
            right += 1
        }
        
        var t = 0
        left = leftIn
        while left <= rightIn {
            n[left] = temp[t]
            left += 1
            t += 1
        }
        
    }
}

算法思想:利用归并的思想实现的排序方法,该算法采用经典的分治(divide-and-conquer)策略(分治法将问题分(divide)成一些小的问题然后递归求解,而治(conquer)的阶段则将分的阶段得到的各答案"修补"在一起,即分而治之)。

github地址:https://github.com/cubegao/LeetCode

标签: 算法

非特殊说明,本博所有文章均为博主原创。

评论啦~