这是一个非常经典的排序算法,O(NlogN)阶。
#include
#include
#include
#include
#define MAX_LENGTH 100
/*Show usage*/
void usage(char * prog)
{
printf("%s Usage:\n", prog);
printf("%s \n", prog);
}
/*Generate and initialize the list*/
int * generate_list(int count)
{
int i;
int * list;
list = (int *)malloc(count*sizeof(int));
if(list == NULL)
{
perror("malloc");
return NULL;
}
/*Initialize the list with integers less than 100*/
srandom((unsigned int)time(NULL));
for (i = 0; i < count ; i ++)
list[i] = random()%100;
return list;
}
/*Show the list*/
void show_list(int * list, int length)
{
int i;
for(i = 0; i < length; i ++)
printf("%d ", list[i]);
printf("\n");
}
/*algorithm*/
int partition(int * list, int first, int last)
{
int left = first;
int right = last;
int pivot = list[left];
while(left < right)
{
while((right > left) && (list[right] >= pivot))
right --;
if(left < right)
{
list[left] = list[right];
left ++;
}
while((left < right) && (list[left] < pivot))
left ++;
if(left < right)
{
list[right] = list[left];
right --;
}
}
list[left] = pivot;
return left;
}
void quick_sort(int * list, int first, int last)
{
if(first < last)
{
int split = partition(list, first, last);
quick_sort(list, first, split-1);
quick_sort(list, split +1, last);
}
return;
}
int main(int argc, char * argv[])
{
int length;
int * list = NULL;
struct timeval tpstart,tpend;
float timeuse;
/*Deal with the arguments*/
if(argc != 2)
{
usage(argv[0]);
exit(127);
}
length = atoi(argv[1]);
if(!length || length > MAX_LENGTH)
{
usage(argv[0]);
exit(129);
}
list = generate_list(length);
if(list == NULL)
exit(128);
else
{
printf("Soruce list:\n");
show_list(list, length);
gettimeofday(&tpstart,NULL);
quick_sort(list, 0, length -1);
gettimeofday(&tpend,NULL);
printf("Ordered list:\n");
show_list(list, length);
timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+ tpend.tv_usec-tpstart.tv_usec;
timeuse/=1000;
printf("time used: %f msec\n", timeuse);
}
free(list);
return 1;
}
阅读(1317) | 评论(0) | 转发(0) |