C language-advanced bubbling && callback function
1. Imitate the function of qsort to implement a general bubble sort.
#include<stdio.h>
#include<stdlib.h>
int MyCmp(const void *eleme1,const void *eleme2){
return *((int*)eleme1) - *((int*)eleme2);//4个字节进行比较
}
void MyQsort(void *num,int len,int size,int (*cmp)(void *eleme1,void *eleme2)){
for (int i = 1; i < len;++i){
for (int j = 0; j < len - i;++j){
if (cmp((char*)num + j*size, (char*)num + (j+1)*size)>0){
for (int k = 0; k < size;++k){
char tmp = *((char*)num + j*size+k);
*((char*)num + j*size+k) = *((char*)num + (j+1)*size+k);
*((char*)num + (j+1)*size+k ) = tmp;
}
}
}
}
}
int main(){
int num[] = {
10,5,8,7,0,6,11,3,2,1};
int len = sizeof(num) / sizeof(num[0]);
MyQsort(num,len,4,MyCmp);
for (int i = 0; i < len;++i){
printf("%d ",num[i]);
}
printf("\n");
system("pause");
return 0;
}
2. Use the library function qsort() to sort, but note that the parameters of this function are more complicated. Take the sort function I wrote as an example,
"MyQsort(void *num,int len,int size,int (*cmp) (void *eleme1,void *eleme2))”, where *num is the sorted array, len is the length of the array, size is the number of bytes in the element, and the last one is a function pointer, which points to one that has two function parameters, and returns The value is a function of type int.
int MyCmp(const void *eleme1,const void *eleme2){
return *((int*)eleme1) - *((int*)eleme2);//int
}
int MyCmp1(const void *eleme1, const void *eleme2){
return *((short*)eleme1) - *((short*)eleme2);//short
}
int MyCmp2(const void *eleme1, const void *eleme2){
return *((char*)eleme1) - *((char*)eleme2);//char
}
//字节不同,比较类型不同
In addition, the qsort function is in #include<stdlib.h>, so the header file must be written first. For different types of sorting, different types of comparison functions are required. Only 3 types are written in the above partial code.
In addition, the callback function is to use the function pointer as a function parameter, and then call the function pointed to by the function pointer by executing the function.