排序

1.归并排序
  1. 归并排序概念
    归并排序核心思想是分治,即将完整数组拆分成更小的数组,最小单位位1,每个小的数组排好序, 然后依次合并数组,递归变小然后再递归变大的过程。
    过程如图
image.png
  1. 代码如下swift版本
let orList:[Int] = [1,2,6,8,4,5,7]

print(orList)

let list = [Int]()

func mergeSort(_ array:[Int])->[Int]{
    var helper = Array(repeating: 0, count: array.count)
    var array = array
    
    mergeSort(&array, &helper, 0, array.count-1)
    return array;
    
}

//拆分,将数组拆分成小单位的数组 单位为1
func mergeSort(_ array:inout [Int], _ helper:inout [Int], _ low: Int, _ height:Int){
    guard low < height else {
        return
    }
    let middel = (height - low)/2 + low
    //拆分左边
    mergeSort(&array, &helper, low, middel)
    print("1 \(low),\(height),\(middel),\(array)")
    //拆分右边
    mergeSort(&array, &helper, middel+1, height)
    print("2 \(low),\(height),\(middel),\(array)")
    //对当前数组排序
    merge(&array, &helper, low, height, middel)
    print("3 \(low),\(height),\(middel),\(array)")
}

func merge(_ array:inout [Int], _ helper:inout [Int], _ low: Int, _ height:Int, _ middel:Int){
    //将目标数组赋值给辅助数组
    for i in low ... height {
        helper[i] = array[i]
    }
    //初始化游标
    var helperLeft = low, helperRight = middel+1
    var current = low
    //因为middle左右的数组都是排好序的,只需要依次将游标处的比较小的放入array数组,
    //这里有两种情况,一种是左游标没走完 后边需要在进行往后赋值,一种是右游标没走完,因为右边已经在后边不需要再重复处理
    while helperLeft <= middel && helperRight <= height {
        if helper[helperLeft] <= helper[helperRight] {
            array[current] = helper[helperLeft]
            helperLeft += 1
        }else{
            array[current] = helper[helperRight]
            helperRight += 1
        }
        current += 1
    }
    
    guard middel - helperLeft >= 0 else {
        return
    }
    //将左数组没有处理完的数据拼接到数组后边
    for i in 0 ... middel - helperLeft {
        array[current+i] = helper[helperLeft+i]
    }
    
}


let array = mergeSort(orList)

print(array)


时间复杂度最好最坏O(nlog2n) 空间复杂度O(n) 稳定排序

2.快速排序

快排是选取数组中某一个元素key,将比key小的放在左边,比key大的放在右边,然后对key左边的数组和key右边的数组分别进行相同的操作。
swift代码如下:

var orList:[Int] = [10,2,6,8,1,4,5,7,89]

print(orList)

func speedSort(_ array:inout [Int]){
    guard array.count > 0 else {
        return
    }
    speedSort(&array, left: 0, right: array.count-1)
}

func speedSort(_ array:inout [Int], left: Int,  right: Int){
    
    guard left < right else {
        return
    }
    
    let temp = array[left]
    var pre = left
    var post = right
    while pre < post {
        while pre < post  && array[post] >= temp {
            post -= 1
        }
        array[pre] = array[post]
        while pre < post && array[pre] <= temp {
            pre += 1
        }
        array[post] = array[pre]
    }
    
    array[pre] = temp
    
    speedSort(&array, left: left, right: pre-1)
    speedSort(&array, left: pre+1, right: right)
    
}

speedSort(&orList)

print(orList)

时间复杂度O(nlog2n) 最坏O(n^2) 空间复杂度O(log2n) 不稳定排序

你可能感兴趣的:(排序)