洛谷:P1177 【模板】快速排序-----理解并死记住。

题目:

分析:本来想找模板记住,水!

但是经典的快排超时了,经典快排:每次选择第一个作为标签元素。

代码:

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]<<' ';
}

加个这个就过了:

在这里插入图片描述

防止算法的退化吧。

代码:

#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]<<' ';
}

猜你喜欢

转载自blog.csdn.net/weixin_42721412/article/details/108543134