Merge sort (thought + C code)

merge sort


Merge sort is an efficient sorting algorithm based on the merge operation. This algorithm is a very typical application of Divide and Conquer.

Ideas:
1. Divide the array in half and half until it is divided into 2 groups;
2. Then sort the array composed of 2 numbers first
3, and then merge the arrays;
4. Recursive like this Going down, a merge sort is formed.

The time complexity of merge sort is O(nlog2n) and the space complexity is O(n)

/*
实现:归并排序算法
*/

#include<iostream>
using namespace std;

void mergeArray(int a[], int start, int mid, int end){
    int *temp = new int[end+1];
    int i = start;
    int j = mid + 1;
    int index = start;
    while (i <= mid&&j <= end){
        if (a[i] < a[j]){
            temp[index++] = a[i++];
        }
        else{
            temp[index++] = a[j++];
        }
    }
    while (i <= mid){
        temp[index++] = a[i++];
    }
    while (j <= end){
        temp[index++] = a[j++];
    }
    for (int k = start; k <= end; k++){
        a[k] = temp[k];
    }
}

void mergeSort(int a[], int start, int end){
    if (start < end){
        int mid = (start + end) / 2;
        mergeSort(a, start, mid);
        mergeSort(a, mid + 1, end);
        //对两个数组进行合并,这2个数组是start ~ mid 以及 mid+1 ~ end
        mergeArray(a, start, mid, end);
    }
}


int main(){
    int a[] = { 7, 5, 6, 4, 3, 2, 1, 3, 5, 7, 9 };

    mergeSort(a,0,10);
    for (int i = 0; i <= 10; i++){
        cout << a[i] << " ";
    }
    system("pause");
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325502819&siteId=291194637