C语言函数qsort中compare详细用法
如题,在compare中。用
/*int x = *(const int *)p;
int y = *(const int *)q;
if (x < y) {
return -1;
} else if (x > y) {
return 1;
}
return 0;*/
和return (*(int *)p-*(int *)q);
的效果不是一样的吗?我想让他升序排序,这不都是升序排序的吗?
能不能给窝详细讲讲呢?我都不懂什么意思,这个qsort用法的具体意思
还有排序这个算法给我普及普及吧,谢谢谢
#include <stdio.h>
#include<stdlib.h>
#define MAXN 10
typedef float ElementType;
int compare (const void *p, const void *q) {
/*int x = *(const int *)p;
int y = *(const int *)q;
if (x < y) {
return -1;
} else if (x > y) {
return 1;
}
return 0;*/
return (*(int *)p-*(int *)q);
}
ElementType Median( ElementType A[], int N );
int main ()
{
ElementType A[MAXN];
int N, i;
scanf("%d", &N);
for ( i=0; i<N; i++ )
scanf("%f", &A[i]);
printf("%.2f\n", Median(A, N));
return 0;
}
/*ElementType Median(ElementType A[],int N)
{
int i,j,m;
ElementType temp;
for(i=0;i<N-1;i++)
for(j=i+1;j<N;j++)
if(A[i]>A[j])
{
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
return A[N/2];
}*/
ElementType Median(ElementType A[],int N)
{
qsort(A, N, sizeof(ElementType), compare);
int i;
for(i=0;i<N;i++)
{
printf("%f ",A[i]);
}
return A[N/2];
}