函数qsort
qsort可不可以对double类型的数组进行排序?可不可以举个例子??
#include <stdio.h> #include <stdlib.h> double values[] = { 40.3, 10.123, 100, 90.8, 20, 25 }; int compare (const void * a, const void * b) { return ( *(double *)a - *(double *)b ); } int main () { int n; qsort (values, 6, sizeof(double), compare); for (n=0; n<6; n++) printf ("%f ",values[n]); return 0; }
#include <stdio.h> #include <time.h> #include <stdlib.h> #define SIZE 20 int compare(const void * p1, const void * p2) { return *(double *)p1 - *(double *)p2; } int main(void) { double buffer[SIZE]; int i; srand((unsigned)time(NULL)); printf("before :\n"); fflush(stdout); for(i = 0; i < SIZE; i++) { buffer[i] = rand() / 3.0; printf("%f\t", buffer[i]); } printf("\nafter :\n"); qsort(buffer, SIZE, sizeof(double), compare); for(i = 0; i < SIZE; i++) printf("%f\t", buffer[i]); return 0; }