qsort 函式實作
- 認識qsort函式
- 關于cmp函式
- 實作qsort函式(此處采取冒泡排序,后續補充快速排序)
認識qsort函式
首先呼叫時先引頭檔案#include<stdlib.h>
base是陣列首元素,num是陣列長度,width是陣列中一個元素占位元組的大小,compare是一個比較函式,來確定比較的方式,若大于則回傳正數,小于回傳負數,相等回傳0


關于cmp函式
由于根據宣告發現此處的e1,e2引數都是void*型別的指標,而此種型別的指標是不能解參考和++/–的,所以我們在比較時都要進行強制型別轉換
typedef struct Stu
{
char name[20];
int age;
float score;
}STU;
int char_cmp(const void* e1,const void *e2){
return strcmp((char *)e1, (char *)e2);//比較字串大小
}
int float_cmp(const void*e1,const void *e2){
return *((float *)e1) - *((float *)e2);//比較浮點型大小
}
int struct_cmp(const void*e1,const void *e2){
return ((STU*)e1)->age - ((STU*)e2)->age;//比較結構體中age的大小
}
int int_cmp(const void *e1,const void *e2){
return *((int *)e1) - *((int *)e2);//比較整型大小
}
特別注意,如要實作升降序

int int_cmp1(const void *e1,const void *e2){
return *((int *)e1) - *((int *)e2);//升序
}
int int_cmp2(const void *e1,const void *e2){
return *((int *)e2) - *((int *)e1);//降序
}
實作qsort函式(此處采取冒泡排序,后續補充快速排序)
void my_swap(char *e1,char *e2,int width){
int i = 0;
for (i = 0; i < width; i++){//因為我們只能獲得j號元素的首地址,此處回圈意義在于對于width個位元組實作挨個交換
char temp = *e1;
*e1 = *e2;
*e2 = temp;
e1++;
e2++;
}
}
void my_qsort(void* base,size_t size,size_t width,int (*cmp)(const void* e1,const void *e2)){
int i = 0, j = 0;
for (i = 0; i < size - 1;i++){
int flag=1;
for (j = 0; j < size - 1 - i;j++){//此處仿照冒泡
if(cmp((char *)base+j*width,(char *)base+(j+1)*width)>0){//(char *)的強制型別轉換為了實作一個位元組一個位元組的加減,+j*width可以找到第j號元素的首地址
my_swap((char *)base + j * width, (char *)base + (j + 1) * width, width);//此處實作交換
flag=0;
}
}
if(flag==1){
break;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/255982.html
標籤:其他
上一篇:chrome瀏覽器如何錄屏
