Algoritmo - Algoritmo de ordenación por fusión

La idea general de la ordenación por fusión es la idea de dividir y conquistar: dividir la matriz por la mitad paso a paso hasta que solo quede un elemento (debe estar en orden en este momento) y luego fusionar las matrices ordenadas una por una. para obtener la matriz ordenada, por lo que se llama clasificación por combinación.

rápido:

import Foundation

var arr = [10,9,8,7,6,4,5,3,2,1]
mergeSort(array: &arr, left: 0, right: arr.count - 1)
print(arr)

func mergeSort(array: inout [Int], left: Int, right: Int) {
    
    
    if left >= right {
    
     return }	//这里一定是大于等于,没有等于号会陷入死循环
    let mid = (left + right) / 2
    mergeSort(array: &array, left: left, right: mid)
    mergeSort(array: &array, left: mid + 1, right: right)
    var temp = Array<Int>.init(repeating: 0, count: right - left + 1)
    var i = left
    var j = mid + 1
    var tempIndex = 0
    //两个子数组,找出最小的数依次合并
    while i <= mid, j <= right {
    
    
        if array[i] < array[j] {
    
    
            temp[tempIndex] = array[i]
            i += 1
            tempIndex += 1
        }else{
    
    
            temp[tempIndex] = array[j]
            j += 1
            tempIndex += 1
        }
    }
    //两个子数组数量不一定相等,把剩下的数字直接合并过来
    //下面两个while实际只会有一个执行
    while i <= mid {
    
    
        temp[tempIndex] = array[i]
        i += 1
        tempIndex += 1
    }
    while j <= right {
    
    
        temp[tempIndex] = array[j]
        j += 1
        tempIndex += 1
    }
    //将临时数组转化到arr中
    for i in 0..<(right - left + 1) {
    
    
        array[left + i] = temp[i]
    }
}

Complejidad temporal: O (n log (n))
es un algoritmo de clasificación relativamente simple y rápido, caracterizado por una alta estabilidad.

Supongo que te gusta

Origin blog.csdn.net/weixin_44758107/article/details/127688726
Recomendado
Clasificación