Common sorting algorithm - merge sort

Merge sort is a divide-and-conquer sorting algorithm. It divides an array into two sub-arrays, sorts the two sub-arrays separately, and then merges the two sorted sub-arrays together to obtain the final sorted array. Merge sort is a stable sorting algorithm.

The process of merge sort is as follows:

1 splits the entire array into two subarrays.
2 Recursively merge and sort the left subarray and recursively merge and sort the right subarray.
3 Merge the two sorted sub-arrays into a final sorted array.

The c language implementation is as follows:

void merge_sort(int arr[], int left, int right) {
    
    
    if (left < right) {
    
    
        int middle = (left + right) / 2;
        merge_sort(arr, left, middle);
        merge_sort(arr, middle + 1, right);
        merge(arr, left, middle, right);
    }
}

void merge(int arr[], int left, int middle, int right) {
    
    
    int i, j, k;
    int n1 = middle - left + 1;
    int n2 =  right - middle;
    int L[n1], R[n2];

    for (i = 0; i < n1; i++)
        L[i] = arr[left + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[middle + 1+ j];

    i = 0;
    j = 0;
    k = left;
    while (i < n1 && j < n2) {
    
    
        if (L[i] <= R[j]) {
    
    
            arr[k] = L[i];
            i++;
        }
        else {
    
    
            arr[k] = R[j];
            j++;
        }
        k++;
    }

    while (i < n1) {
    
    
        arr[k] = L[i];
        i++;
        k++;
    }

    while (j < n2) {
    
    
        arr[k] = R[j];
        j++;
        k++;
    }
}

The advantage of merge sort is that it can guarantee the stability of the sorted array, that is, the relative position of the same element before and after sorting will not change, and its time complexity is O(nlogn), and in most cases, a better result can be obtained performance.

However, the space complexity of merge sort is O(n). If the amount of data is relatively large, it may take up more space, so merge sort is not suitable for scenarios with a particularly large amount of data.

The code can also be simplified:

void merge_sort(int q[], int l, int r)
{
    
    
    if (l >= r) return;

    int mid = l + r >> 1;
    merge_sort(q, l, mid);
    merge_sort(q, mid + 1, r);

    // 归并的过程
    int k = 0, i = l, j = mid + 1;
    while (i <= mid && j <= r)
        if (q[i] <= q[j]) tmp[k ++ ] = q[i ++ ];
        else tmp[k ++ ] = q[j ++ ];

    // 扫尾
    while (i <= mid) tmp[k ++ ] = q[i ++ ];
    while (j <= r) tmp[k ++ ] = q[j ++ ];

    // 物归原主
    for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = tmp[j];  // i循环的是原数组,j循环的是临时数组。
}

Merge sort is stable, and the time complexity is O(nlogn), and the space complexity is O(n). If the amount of data to be sorted is not particularly large and the stability of the sort is required, merge sort is a good choice.

Guess you like

Origin blog.csdn.net/sorcererr/article/details/128700614