Study notes: quick sort

Basic steps:
1. Determine the dividing point x (a[l], a[r], a[l+r>>1])
2. Divide the interval (less than x on one side, and greater than x on the other side)
3. Recursively process the left and right ends

const int N = 1e5+5;
int n,a[N];

void quick_sort(int a[],int l,int r)
{
    
    
	if(l>=r)	return ;
	
	int i=l-1,j=r+1,x=a[l+r>>1];
	while(i<j)
	{
    
    
		while(a[++i]<x);
		while(a[--j]>x);
		if(i<j)	swap(a[i],a[j]);
	}
	quick_sort(a,l,j);
	quick_sort(a,j+1,r);
}

int main()
{
    
    
	scanf("%d",&n);
	for(int i=0;i<n;i++)	scanf("%d",&a[i]);
	quick_sort(a,0,n-1);
	for(int i=0;i<n;i++)	printf("%d ",a[i]);
	return 0;
}

Clever use of quick sort: find the k-th smallest number in the array

Because the dividing point x is selected in the quick sorting process, then the numbers on the left of the array are less than or equal to x, and the numbers on the right are greater than or equal to x. Assume that there are m numbers on the left of the array, and the first m numbers are on the left.
If m>= k, then the k-th smallest number is on the left, and recursively to the left.
Otherwise, the k-th smallest number is on the right, and the k-th smallest number is on the right, and the km-th smallest number is on the right.

#include<cstdio>
#include<cmath>
#include<ctime>
#include<cstring>
#include<iostream>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<string>
#include<vector>
#define ll long long
#define ull unsigned long long
#define up_b upper_bound
#define low_b lower_bound
#define m_p make_pair
#define mem(a) memset(a,0,sizeof(a))
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define inf 0x3f3f3f3f
#include<algorithm>
using namespace std;

inline ll read()
{
    
    
	ll x=0,f=1; char ch=getchar();
	while(ch<'0'||ch>'9')	{
    
     if(ch=='-') f=-1; ch=getchar(); }
	while('0'<=ch&&ch<='9')	x=x*10+ch-'0', ch=getchar();
	return f*x;
}

const int N = 1e5+5;
int n,k,a[N];

int quick_sort(int l,int r,int k)
{
    
    
	if(l==r)	return a[l];
	
	int i=l-1,j=r+1,x=a[l+r>>1];
	while(i<j)
	{
    
    
		while(a[++i]<x);
		while(a[--j]>x);
		if(i<j)	swap(a[i],a[j]);
	}
	int nums=j-l+1;//左边的个数
	if(nums>=k)	quick_sort(l,j,k);
	else	quick_sort(j+1,r,k-nums);
}

int main()
{
    
    
	cin>>n>>k;
	for(int i=0;i<n;i++)	scanf("%d",&a[i]);
	cout<<quick_sort(0,n-1,k)<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_50815157/article/details/113417283
Recommended