Quick sort, merge sort template

 A brief summary of learning sorting algorithms on acwing


Quick sort

Implementation principle: Find a reference number x, and use this reference number to divide the array into two groups each time (the left part is less than x, and the right part is greater than or equal to x). Continue to perform the same operation with the divided groups until finally there is only one number, that is (l == r). At this time, the sorting of the subsequences is completed, and when all the subsequences are sorted, the entire q array is also completed. Sorted.

#include <iostream>

using namespace std;

const int N = 100010;

int q[N];

void quick_sort(int q[], int l, int r)
{
    if (l == r) return; //当数组里面只有一个数时,完成排序
    
    //将左端点和右端点分别往左和右挪一位
    int i = l - 1, j = r + 1, x = q[l + r >> 1]; //相当于/2
    while (i < j)
    {
        do i ++ ; while (q[i] < x); //先把i往右移,如果指到的数大于等于x就停下
        do j -- ; while (q[j] > x); //先把j往左移,如果指到的数小于等于x就停下
        if (i < j) swap(q[i], q[j]); //交换两个位置的数
    }
    //递归处理子序列
    quick_sort(q, l, j); //左半部分
    quick_sort(q, j + 1, r); //右半部分
}

int main()
{
    int n;
    scanf("%d", &n);

    for (int i = 0; i < n; i ++ ) scanf("%d", &q[i]);

    quick_sort(q, 0, n - 1);

    for (int i = 0; i < n; i ++ ) printf("%d ", q[i]);

    return 0;
}

Merge sort 

Core idea: One divides into two, two merges into one. It means that an unordered array is divided into two and then two (until it is divided into the smallest unit array with only one number, and a number is of course ordered), and then continues to merge and merge from the smallest unit array until it is finally synthesized into one Completely sorted array.

#include <iostream>

using namespace std;

const int N = 1e5 + 10;

int a[N], tmp[N];

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;
    //比较两个数组里的数哪个数更小,就加入到tmp数组中储存
    while (i <= mid && j <= r)
        if (q[i] <= q[j]) tmp[k ++ ] = q[i ++ ]; 
        else tmp[k ++ ] = q[j ++ ];
    //将留下的尾巴接入tmp数组
    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]; //更新q数组
}

int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i ++ ) scanf("%d", &a[i]);

    merge_sort(a, 0, n - 1);

    for (int i = 0; i < n; i ++ ) printf("%d ", a[i]);

    return 0;
}

Guess you like

Origin blog.csdn.net/Radein/article/details/134759570