算法学习---关于快速排序,数据呈现基本有序和完全无序时候导致的时间复杂度增n^2的解决方案

来源:互联网 发布:中医古籍数据库公司 编辑:程序博客网 时间:2024/05/29 17:52

             前言--------------------大笑经过了一段考研学习,也该是时候准备准备复试或者准备今后的工作面试了,那么对于我之前喜欢暴力解法的初级童鞋来说,在算法学习中其实挺迷茫的,所以就想借助写个博客加深对算法学习的深刻,希望有看到的大神多多指教,嘿嘿,下面直接来代码。

  

                                                         快排中时间复杂度增大解决方案


我们采取随机取主元对每个区间进行大小分隔,其时间复杂度虽然为o(n^2) ,但其对任意输入数据的期望时间复杂度都能达到o(nlogn);


                         

#include<cstdio>
#include<stdlib.h>
#include<time.h>
#include<math.h>



//快速排序 针对有序 反序的 改进的 


const int maxn=100;


int a[maxn];




int randPartition(int a[],int left,int right){

void swap(int a,int b);

int p=(round((1.0*rand()/RAND_MAX*(right-left)+left)));


    
     int tmep1=a[left];
     a[left]=a[p];
     a[p]=tmep1;



    int temp=a[left];
    
    while(left<right){
   
    while(left<right && temp<a[right]) --right;
   
a[left]=a[right];    
   
   
    while(left<right && a[left]<=temp) ++left;
   
a[right]=a[left];    
   
}

a[left]=temp;

return left;


}



void quickSort(int a[], int left ,int right){

 if(left<right){
 
  int mid=randPartition(a,left,right);
       
        quickSort(a,left,mid-1);
        
quickSort(a,mid+1,right);


 
 }

}




int main(){


srand((unsigned)time(NULL));

printf("please enter the number  you want : \n");

int n;

scanf("%d",&n);


printf("you will enter %d numbers : \n",n);

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


printf("now, i am computing...\n");

quickSort(a,0,n-1);


for(int i=0;i<n;++i){

printf("%d ",a[i]);

if(i!=0 && i%9==0){
printf("\n");
}

}




return 0;



}


这是我人生中第一篇博客,希望大家多多指教了。




















































1 0
原创粉丝点击