Luo Gu: P1177 [Template] Quick sort-----understand and remember.

topic:

Analysis: I wanted to find a template to remember, water!

But the classic fast queue timed out, classic fast queue: select the first one as the label element each time.

Code:

using namespace std;
int m;
int A[100005];
void qsort(int low,int high)
{
    
    
 if(low>=high) return;
 int i=low;
    int j=high+1;
    int key=A[low];
    while(1)
    {
    
    
     while(A[++i]<key) if(i==high) break;
     while(A[--j]>key) if(j==low) break;
     if(i>=j) break;
     int temp=A[i];
     A[i]=A[j];
     A[j]=temp;
 }
 int temp=A[low];
     A[low]=A[j];
     A[j]=temp;
 qsort(low,j-1);
 qsort(j+1,high);
}
int main()
{
    
    
 int m=1;
 cout<<(m++);
 cin>>m;
 for(int i=0;i<m;i++) cin>>A[i];
 qsort(0,m-1);
 for(int i=0;i<m;i++) cout<<A[i]<<' ';
}

Just add this:

Insert picture description here

Prevent the degradation of the algorithm.

Code:

#include<bits/stdc++.h>
using namespace std;
int m;
int A[100005];
void qsort(int low,int high)
{
    
    
 if(low>=high) return;
 int c=(low+high)/2;
 swap(A[c],A[low]);
 int i=low;
    int j=high+1;
    int key=A[low];
    while(1)
    {
    
    
     while(A[++i]<key) if(i==high) break;
     while(A[--j]>key) if(j==low) break;
     if(i>=j) break;
     int temp=A[i];
     A[i]=A[j];
     A[j]=temp;
 }
 int temp=A[low];
     A[low]=A[j];
     A[j]=temp;
 qsort(low,j-1);
 qsort(j+1,high);
}
int main()
{
    
    
 cin>>m;
 for(int i=0;i<m;i++) cin>>A[i];
 qsort(0,m-1);
 for(int i=0;i<m;i++) cout<<A[i]<<' ';
}

Guess you like

Origin blog.csdn.net/weixin_42721412/article/details/108543134