#include <stdio.h>
#include <Windows.h>
#include <stdlib.h>
#include <assert.h>
#pragma warning(disable:4996)
int cmp_int(void *x, void *y)//升序排列
{
int *_x = (int*)x;
int *_y = (int*)y;
if (*_x > *_y)
{
return 1;
}
else if (*_x < *_y)
{
return -1;
}
else
return 0;
}
int main()
{
int arr[] = { 1, 5, 63, 52, 74, 33, 1, 21, 56, 5, 4 };
int size = sizeof(arr) / sizeof(arr[0]);
qsort(arr, size, sizeof(char *), cmp_int);
system("pause");
return 0;
}
这里用到一个函数 qsort:
它可以对任意类型进行排序,返回值为int类型。
而上述代码中的cmp_int就是qsort的回调函数。
上述代码为升序排列,若想变为降序排列,读者只需将cmp_int 函数中返回值1和-1调换位置即可。