函数原型
void qsort(void *__base, size_t __nel, size_t __width,
int );
实例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compareInt(const void *a, const void *b) {
return *(int *) a - *(int *) b;
}
int compareString(const void *a, const void *b) {
return strcmp((char *) a, (char *) b);
}
int main() {
const int len = 10;
int a[len];
for (int i = 0; i < len; ++i) {
a[i] = rand() % 100;
}
printf("排序前\n");
for (int j = 0; j < len; ++j) {
printf("%d\t", a[j]);
}
printf("\n");
qsort(a + 4, len - 4, sizeof(int), compareInt);
printf("排序后\n");
for (int j = 0; j < len; ++j) {
printf("%d\t", a[j]);
}
printf("\n");
char names[5][10] = {"WebStorm", "Pycharm", "IntelliJ", "CLion", "PhpStorm"};
printf("排序前\n");
for (int k = 0; k < 5; ++k) {
printf("%10s\t", names[k]);
}
printf("\n");
qsort(names, 5, 10 * sizeof(char), compareString);
printf("排序后\n");
for (int k = 0; k < 5; ++k) {
printf("%10s\t", names[k]);
}
return 0;
}
排序前
7 49 73 58 30 72 44 78 23 9
排序后
7 49 73 58 9 23 30 44 72 78
排序前
WebStorm Pycharm IntelliJ CLion PhpStorm
排序后
CLion IntelliJ PhpStorm Pycharm WebStorm