Quick sort and merge sort template

Quick sort template

 

 

 

The idea of ​​quick sort is divide and conquer:

Define two pointers, i, j. If the value pointed to by i is less than x, then i will move one bit backward until the number pointed to by i is greater than or equal to x and stop moving; in the same way, if the value pointed to by the j pointer is greater than x, then j The pointer moves forward one position until the number pointed to by j is less than or equal to x and stops moving; when both pointers stop moving, exchange the value pointed to by the pointer...

The algorithm idea can refer to the following figure:

It should be noted that if the demarcation point is x = q[l] or x = q[r], the worst case when taking two paragraphs is n-square complexity, and there will be timeouts on some oj

#include<iostream>
#include<algorithm>
using namespace std;

const int N = 1e6 + 10;
int n;
int q[N];

void quick_sort(int q[],int l,int r)
{
    if (l >= r) return;
    //如果分界点取x = q[l]或者x = q[r],取两段最坏情况n方复杂度,在一些oj上会出现超时的情况
    //i = l - 1,j = r + 1,而不是使指针正好指到首尾两端,暂时记住即可
    int x = q[(l + r) / 2],i = l - 1,j = r + 1;
    while (i < j)
    {
        //只要i < j,两指针同时向中间移动
        do i++; while(q[i] < x);
        do j--; while(q[j] > x);
        //如果无法移动,则可以交换两数位置
        if (i < j) swap(q[i],q[j]);
    }
    //再进行递归排序
    quick_sort(q,l,j);
    quick_sort(q,j + 1,r);
}

int main()
{
    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 template:

 

#include<iostream>
using namespace std;

const int N = 1e6 + 10;
int q[N],temp[N];
int 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 i = l,j = mid + 1;
    int k = 0;
    //i可以移动到mid的位置,j可以移动到r的位置
    while (i <= mid && j <= r) 
    {
        //将较小的数存储到数组中
        if (q[i] <= q[j]) temp[k++] = q[i++];
        else temp[k++] = q[j++];
    }
    //若有剩余,将剩余的数直接存储到数组中
    while (i <= mid) temp[k++] = q[i++];
    while (j <= r) temp[k++] = q[j++];
    //将结果返回给q数组
    for (int i = l,j = 0;i <= r;i++,j++)  q[i] = temp[j];
}
int main()
{
    scanf("%d",&n);
    for (int i = 0;i < n;i++) scanf("%d",&q[i]);
    merge_sort(q,0,n - 1);
    for (int i = 0;i < n;i++) printf("%d ",q[i]);
    return 0;
}

Refer to the figure above to understand the merge sort code

Guess you like

Origin blog.csdn.net/smallrain6/article/details/106035606