这个用qsort排序的程序的子函数为什么能实现排序?
这个程序是从网上改编来了,对于子函数有点不理解,为什么返回*p - *q;就是升序排列,返回(*p - *q) * (-1);就是降序排列?这应该是个数学问题?
#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include "math.h"
#include "stdlib.h"
int compi(const void *a, const void *b);
int compd(const void *a, const void *b);
int main(void)
{
int array[100];
int len, i, choice;
printf("Please input the number of the integer you want to print:");
scanf("%d", &len);
puts("Create a array:");
for(i=0; i<len; i++)
{
scanf("%d", &array[i]);
}
puts("Please choose the kind you want to sort the array.");
puts("1) representive to sort the array by increaing");
puts("2) representive to sort the array by reducing");
scanf("%d", &choice);
switch (choice)
{
case 1 : qsort(array, len, sizeof(int), compi);break;
case 2 : qsort(array, len, sizeof(int), compd);break;
}
if(choice == 1)
{
puts("Sort the array by increaing:");
}
else
{
puts("Sort the array by reducing:");
}
for(i=0; i<len; i++)
{
printf("%d ", array[i]);
}
puts("\n");
return 0;;
}
int compi(const void *a, const void *b)
{
const int *p = (const int *)a;
const int *q = (const int *)b;
return *p - *q;
}
int compd(const void *a, const void *b)
{
const int *p = (const int *)a;
const int *q = (const int *)b;
return (*p - *q) * (-1);
}
正好一个升序一个降序
[解决办法]
*p>*q时 *p - *q>0;交换两个元素位置,升序
*p<*q时( *p - *q) *(-1)>0;交换两个元素位置,降序
[解决办法]
qsort的那个比较函数,主要是看函数返回值是大于0或者小于0.
大于0,升序,小于0,降序.
我是这么理解的.
[解决办法]
这么写其实是不对的……不过数据值小的时候没啥问题。
[解决办法]
两个比较函数,就是对“大或小”的看法而已。
这样理解吧:
如果考1分比考2分差(小),就升序了
如果被扣1分比被扣2分好(大),就降序了