使用这个简单的样本,目前订购了6个数字5,4,3,2,1,0并将其排序为:0,1,2,3,4,5
#include <stdio.h>
#include <stdlib.h>
int values[] = {5,4,3,2,1,0};
int sizeOfArray = sizeof(values)/sizeof(int);
int cmpfunc (const void * a, const void * b)
{
printf("Comparing %d and %d \n",*(int*)a, *(int*)b);
return ( *(int*)a - *(int*)b );
}
int main () {
int n;
printf("Size of Array : %d\n", sizeOfArray);
printf("Before sorting the list is: \n");
for( n = 0 ; n < sizeOfArray; n++ ) {
printf("%d ", values[n]);
}
printf("\n");
qsort(values, sizeOfArray, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < sizeOfArray; n++ ) {
printf("%d ", values[n]);
}
return(0);
}
在cmpfunc函数中添加了一个printf命令,用于显示在调用每个函数时要比较的数字。
Size of Array : 6
Before sorting the list is:
5 4 3 2 1 0
Comparing 4 and 3
Comparing 5 and 3
Comparing 5 and 4
Comparing 1 and 0
Comparing 2 and 0
Comparing 2 and 1
Comparing 3 and 0
Comparing 3 and 1
Comparing 3 and 2
After sorting the list is:
0 1 2 3 4 5
请注意,应用程序仅调用cmpfunc 9次。 我本来期望这个函数被多次调用。 另请注意,5或4永远不会与2或1进行比较。
是否有人能够解释幕后发生的事情,导致此例程如此高效?
答案 0 :(得分:1)
研究&#34; QuckSort&#34;它更有意义。 我修改了示例以添加额外的print语句。
#include <stdio.h>
#include <stdlib.h>
int values[] = { 5,4,3,2,1,0};
int sizeOfArray = sizeof(values)/sizeof(int);
int cmpfunc (const void * a, const void * b)
{
int n = 0;
printf("Comparing %d and %d current array looks like this :" ,*(int*)a, *(int*)b);
for( n = 0 ; n < sizeOfArray; n++ )
{
printf("%d ", values[n]);
}
printf("\n");
return ( *(int*)a - *(int*)b );
}
int main () {
int n;
printf("Size of Array : %d\n", sizeOfArray);
printf("Before sorting the list is: \n");
for( n = 0 ; n < sizeOfArray; n++ )
{
printf("%d ", values[n]);
}
printf("\n");
qsort(values, sizeOfArray, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < sizeOfArray; n++ ) {
printf("%d ", values[n]);
}
return(0);
}
阅读维基百科页面并打印出阵列的状态,每次有意义发生了什么,它与图表流程相匹配。
Size of Array : 6
Before sorting the list is:
5 4 3 2 1 0
Comparing 4 and 3 current array looks like this :5 4 3 2 1 0
Comparing 5 and 3 current array looks like this :5 3 4 2 1 0
Comparing 5 and 4 current array looks like this :5 3 4 2 1 0
Comparing 1 and 0 current array looks like this :3 4 5 2 1 0
Comparing 2 and 0 current array looks like this :3 4 5 2 0 1
Comparing 2 and 1 current array looks like this :3 4 5 2 0 1
Comparing 3 and 0 current array looks like this :3 4 5 0 1 2
Comparing 3 and 1 current array looks like this :3 4 5 0 1 2
Comparing 3 and 2 current array looks like this :3 4 5 0 1 2
After sorting the list is:
0 1 2 3 4 5