Algorithme - Algorithme de tri par fusion

L'idée générale du tri par fusion est l'idée de diviser pour mieux régner. Divisez le tableau en deux étape par étape jusqu'à ce qu'il ne reste qu'un seul élément (il doit être en ordre à ce moment-là), puis fusionnez les tableaux ordonnés un par un. pour obtenir le tableau trié.array, on l'appelle donc tri par fusion.

rapide:

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]
    }
}

Complexité temporelle : O(n log(n))
est un algorithme de tri relativement simple et rapide, caractérisé par une grande stabilité.

Je suppose que tu aimes

Origine blog.csdn.net/weixin_44758107/article/details/127688726
conseillé
Classement