日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

C语言模拟实现标准库函数之qsort() 2

發布時間:2023/11/30 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C语言模拟实现标准库函数之qsort() 2 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

總結

以上是生活随笔為你收集整理的C语言模拟实现标准库函数之qsort() 2的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。