快速排序的算法:快速排序算法



这是个非常经典排序算法O(NlogN)阶

# <stdlib.h>
# <stdio.h>
# <sys/time.h>
# <time.h>
# MAX_LENGTH 100
/*Show usage*/
void usage(char * prog)
{
prf(\"%s Usage:\\n\", prog);
prf(\"%s <the count of numbers to sort (should be less than 100)>\\n\", prog);
}
/*Generate and initialize the list*/
* generate_list( count)
{
i;
* list;
list = ( *)malloc(count*());
(list NULL)
{
perror(\"malloc\");
NULL;
}
/*Initialize the list with egers less than 100*/
srandom((unsigned )time(NULL));
for (i = 0; i < count ; i )
list[i] = random%100;
list;
}
/*Show the list*/
void show_list( * list, length)
{
i;
for(i = 0; i < length; i )
prf(\"%d \", list[i]);
prf(\"\\n\");
}
/*algorithm*/
partition( * list, first, last)
{
left = first;
right = last;
pivot = list[left];
while(left < right)
{
while((right > left) && (list[right] >= pivot))
right --;
(left < right)
{
list[left] = list[right];
left ;
}
while((left < right) && (list[left] < pivot))
left ;
(left < right)
{
list[right] = list[left];
right --;
}
}
list[left] = pivot;
left;
}
void quick_sort( * list, first, last)
{
(first < last)
{
split = partition(list, first, last);
quick_sort(list, first, split-1);
quick_sort(list, split +1, last);


}
;
}
( argc, char * argv)
{
length;
* list = NULL;
struct timeval tpstart,tpend;
float timeuse;
/*Deal with the arguments*/
(argc != 2)
{
usage(argv[0]);
exit(127);
}
length = atoi(argv[1]);
(!length || length > MAX_LENGTH)
{
usage(argv[0]);
exit(129);
}
list = generate_list(length);
(list NULL)
exit(128);

{
prf(\"Soruce list:\\n\");
show_list(list, length);
gettimeofday(&tpstart,NULL);
quick_sort(list, 0, length -1);
gettimeofday(&tpend,NULL);
prf(\"Ordered list:\\n\");
show_list(list, length);
timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+ tpend.tv_usec-tpstart.tv_usec;
timeuse/=1000;
prf(\"time used: %f msec\\n\", timeuse);
}
free(list);
1;
}


Tags:  快速排序 快速排序算法代码 实现快速排序算法 快速排序的算法

延伸阅读

最新评论

发表评论