zoukankan      html  css  js  c++  java
  • 归并排序

    介绍

    归并排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的,然后再把有序子序列合并为整体有序序列。

    过程

    第一步:申请空间,使之大小为两个已经排序序列之和,该空间用来存放合并后的序列;

    第二步:设定两个指针,最初位置为两个已经排序序列的起始位置;

    第三步:比较两个指针所指向的元素,将相对较小的元素放入到合并空间,并移动指针到下一个位置。

    重复步骤3直到某一指针超出序列,将另一序列剩下的所有元素直接复制到合并序列尾。

    代码

    #include<iostream>
    using namespace std;
    void Merge(int sourceArr[],int tempArr[],int startIndex,int midIndex,int endIndex){
        int i = startIndex, j = midIndex + 1, k = startIndex;
        while (i != midIndex + 1 && j != endIndex + 1){
            if (sourceArr[i] > sourceArr[j]){
                tempArr[k++] = sourceArr[j++];
            }
            else{
                tempArr[k++] = sourceArr[i++];
            }
        }
        while (j != endIndex + 1){
            tempArr[k++] = sourceArr[j++];
        }
        while (i != midIndex + 1){
            tempArr[k++] = sourceArr[i++];
        }
    
        for (i = startIndex; i <= endIndex; i++){
            sourceArr[i] = tempArr[i];
        }
    }
    
    //内部使用递归
    void MergeSort(int sourceArr[], int tempArr[], int startIndex, int endIndex){
        int midIndex;
        if (startIndex < endIndex){
            midIndex = (startIndex + endIndex) / 2;
            MergeSort(sourceArr, tempArr, startIndex, midIndex);
            MergeSort(sourceArr, tempArr, midIndex + 1, endIndex);
            Merge(sourceArr, tempArr, startIndex, midIndex, endIndex);
        }
    }
    
    
    int main(){
        int a[8] = { 50, 10, 20, 30, 70, 40, 80, 60 };
        int i, b[8];
        MergeSort(a, b, 0, 7);
        for (i = 0; i < 8; i++){
            cout << a[i] << " ";
        }
        return 0;
    }

    时间复杂度

    0(n*log(n))

    空间复杂度

    0(n)

  • 相关阅读:
    Python Day14
    Python Day13
    Python Day12
    Python Day11
    Python Day10
    Python Day9
    Python Day8
    Python Day7
    Python Day6
    Python Day5
  • 原文地址:https://www.cnblogs.com/bluebean/p/5847290.html
Copyright © 2011-2022 走看看