C语言模拟实现标准库函数之qsort() <1>
https://blog.csdn.net/csdn_kou/article/details/80158194
排序数字
int int_cmp(const void *elem1, const void *elem2)
{
return *(int *)elem1 - *(int *)elem2;
}int main()
{
int arr[] = { 9,8,7,6,5,4,3,2,1 };
int size = sizeof(arr) / sizeof(arr[0]);
int i = 0;
qsort(arr, size, sizeof(int), int_cmp);
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
system("pause");
return 0;
}
排序字符串
int compare(const void * a, const void * b)
{return (*(char*)a - *(char*)b);
}int main()
{char s[4][6] = { "dog","cat","pig" ,"tiger"}; //字符串数组排序 qsort(s, sizeof(s)/sizeof(s[0]), sizeof(s[0]), compare); //sizeof(s[0])=sizeof(char)for (int i = 0; i<sizeof(s) / sizeof(s[0]); i++)printf("%s\n", s[i]);system("pause");return 0;
}
按字典顺序排列
#include<stdio.h>
#include <stdlib.h>
#include <string.h>int compare(const void * a, const void * b)
{return (*(char*)a - *(char*)b);
}int main()
{int n;scanf("%d", &n);char str[1000][1000];char temp[1000];for (int i = 0; i<n; i++){scanf("%s", &str[i]);}*str[n] = '\0';qsort(str, n, sizeof(str[0]), compare); //sizeof(s[0])=sizeof(char)for (int i = 0; i<n; i++){printf("%s\n", str[i]);}return 0;
}
结构体排序
- 1.例一
(改编自网上代码)
#include <stdio.h>
#include <stdlib.h>
#define NUM 5
typedef struct
{int date;int value;
}X_S;int cmpfun1(const void * a, const void * b)
{X_S * p1 = (X_S *)a;X_S * p2 = (X_S *)b;return p1->value - p2->value;
}int cmpfun2(const void * a, const void * b)
{X_S * p1 = (X_S *)a;X_S * p2 = (X_S *)b;return p1->value < p2->value;
}int quickSort()
{X_S Xlist[NUM];int Ilist[NUM];int i = 0;for (i = 0; i < NUM; i++){Xlist[i].date = i + 1;//double t = (double)i - 50.3;//Xlist[i].value = (int)(t * t + 5.6);Xlist[i].value = rand();}printf("\n-------------before sorted-------------\n");for (i = 0; i < NUM; i++){printf("num : %3d, value : %4d\n", Xlist[i].date, Xlist[i].value);}qsort(Xlist, NUM, sizeof(X_S), cmpfun1);printf("\n-------------after sorted-------------\n");for (i = 0; i < NUM; i++){printf("num : %3d, value : %4d\n", Xlist[i].date, Xlist[i].value);}qsort(Xlist, NUM, sizeof(X_S), cmpfun2);printf("\n-------------after sorted-------------\n");for (i = 0; i < NUM; i++){printf("num : %3d, value : %4d\n", Xlist[i].date, Xlist[i].value);}return 0;
}int main()
{quickSort();system("pause");return 0;
}
- 例二
简陋的通讯录
https://blog.csdn.net/csdn_kou/article/details/80287640