c编程练习之快速排序

太久没有编过程序,今天起开始打算利用一些小时间复习编程。从排序算法入手,试了一下快速排序,还是花了不少时间。采用了随机选择参照物的方法,随机化快速排序

对于绝大多数输入数据达O(nlogn)期望时间复杂度

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

#define N 5

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

{  

int i=left,j=right,k,q,temp;

 if(i<j)  

{  

srand((unsigned)time(NULL));  

k=rand()%(right-left)+left;  

q=a[k];

 while(i<j)  {

  if(a[i]<q)   

 i++;

  else if(a[j]>q)   

 j--;  

 else if(a[i]==a[j])   

 i++;   

else  

 {   

 temp=a[i];   

 a[i]=a[j];   

 a[j]=temp;   

}

 }  

quickSort(a,left,i-1);

 quickSort(a,i+1,right);  

}

}

void main()

{

 int a[N]={0},i;

 printf("Please enter the array:\n");

 for(i=0;i<N;i++)

 {  

 scanf("%d",&a[i]);

 }

 printf("The array unsorted:");  

for(i=0;i<N;i++)

 {   

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

}

 printf("\n");

 quickSort(a,0,N);

 printf("The array sorted:");

 for(i=0;i<N;i++)

 {  

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

 }

 printf("\n");

}

posted on 2014-04-19 18:53  路子  阅读(88)  评论(0)    收藏  举报

导航