功 能: 快速排序
头文件:stdlib.h
用 法: void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));
参数:
1 待排序数组首元素的地址
2 数组中待排序元素数量
3 各元素的占用空间大小
4 指向函数的指针,用于确定排序的顺序
注意:数组中可以存储数字,字符,或者结构体都行。
数字:
#include <stdio.h>
#include <stdlib.h> int compInc(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
} int compDec(const void *a, const void *b)
{
return *(int *)b - *(int *)a;
} int main()
{
int a[] = { ,,,, };
int len = ;
int i; printf("递增排序结果:\n");
qsort(a, len, sizeof(a[]), compDec);
for (i = ; i < len; i++)
{
printf("%d ", a[i]);
}
printf("\n"); return ;
}
字符串长度排序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 12
#define N 20 int compareInc(const void *a, const void *b)
{
return strlen((char *)a) - strlen((char*)b);//字符串长度比较
} int compareDec(const void *a, const void *b)
{
return strlen((char *)b) - strlen((char*)a);
} int main(void)
{
int i;
char s[M][N] =
{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
}; qsort(s, M, sizeof(char) * N, compareInc);
for (i = ; i < M; i++)
printf("%s\n", s[i]); printf("\n"); qsort(s, M, sizeof(char) * N, compareDec);
for (i = ; i < M; i++)
printf("%s\n", s[i]); return ;
}
字符串大小排序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 12
#define N 20 int compare1(const void *a, const void *b)
{
return *(char *)a - *(char*)b;//字符串大小比较
} int compare2(const void *a, const void *b)
{
return *(char *)b - *(char*)a;
} int main(void)
{
int i;
char s[M][N] =
{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
}; qsort(s, M, sizeof(char) * N, compare1);
for (i = ; i < M; i++)
printf("%s\n", s[i]); printf("\n"); qsort(s, M, sizeof(char) * N, compare2);
for (i = ; i < M; i++)
printf("%s\n", s[i]); return ;
}
结构体:
#include <stdio.h>
#include <stdlib.h>
#define N 6 typedef struct
{
char name[];
int score; }Student; int compare1(const void *a, const void *b)
{
return ((Student*)a)->score - ((Student*)b)->score;//以结构体的成绩排序
} int compare2(const void *a, const void *b)
{
return *(((Student*)a)->name) - *(((Student*)b)->name);//以结构体的学生姓名排序
} void print(Student s)
{
printf("%-15s : %d\n", s.name, s.score);
} int main()
{
Student s[N] =
{
"Zhang San", ,
"Li Si", ,
"You", ,
"I", ,
"He", ,
"She",
}; int i;
qsort(s, N, sizeof(Student), compare1);
for (i = ; i < N; i++)
{
print(s[i]);
} printf("\n"); qsort(s, N, sizeof(Student), compare2);
for (i = ; i < N; i++)
{
print(s[i]);
} return ;
}