C語言快速排序函數(shù)用法(qsort)
更新時間:2021年08月24日 16:15:50 作者:keep_hardworking
這篇文章主要為大家詳細介紹了C語言的快排函數(shù)用法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C語言快排函數(shù)用法,供大家參考,具體內(nèi)容如下
#include <stdio.h> #include <stdlib.h> #include <string.h> struct student { int id; char name[12]; char sex; }; int compare(const void* a,const void* b)//基本數(shù)據(jù)類型排序 { return *(char*)a-*(char*)b;//從小到大 //取值//強轉(zhuǎn)為相應(yīng)類型的指針?。? } int compare_struct(const void* a,const void* b) { return (*(struct student*)a).id-((struct student*)b)->id; //注意優(yōu)先級誒!//否則報錯在非結(jié)構(gòu)體中。。。 } int compare_struct_duoji(const void* a,const void* b)//多級排序 { struct student student_a=*(struct student*)a; struct student student_b=*(struct student*)b; if(student_a.id==student_b.id) { return student_a.sex-student_b.sex; } else { return student_a.id-student_b.id; } } void main() { //*************char型************* char a[5]="hello"; qsort(a,5,sizeof(a[0]),compare); //元素個數(shù)//元素大小//函數(shù)指針 int i; for(i=0;i<5;i++) printf("%c ",a[i]); printf("\n"); //************struct型************ struct student e[4]={{100,"chen",'m'},{100,"li",'f'}, \ {70,"wang",'f'},{100,"zhang",'m'}}; qsort(e,4,sizeof(e[1]),compare_struct_duoji); for(i=0;i<4;i++) printf("%d %s %c\n",e[i].id,e[i].name,e[i].sex); }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C語言中 int main(int argc,char *argv[])的兩個參數(shù)詳解
這篇文章主要介紹了C語言中 int main(int argc,char *argv[])的兩個參數(shù)詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03Qt連接數(shù)據(jù)庫并實現(xiàn)數(shù)據(jù)庫增刪改查的圖文教程
QT連接數(shù)據(jù)庫是應(yīng)用開發(fā)的常用基礎(chǔ)操作,經(jīng)過實驗我總結(jié)了一些例程,下面這篇文章主要給大家介紹了關(guān)于Qt連接數(shù)據(jù)庫并實現(xiàn)數(shù)據(jù)庫增刪改查的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-04-04