模拟实现库函数qsort

手动实现buble_sort函数

1.模拟整型数组的冒泡排序

void buble(int arr[],int sz){
   for (int i = 0; i < sz-1; i++)
   {
    for (int j = 0; j < sz-1-i; j++)
    {
        if (arr[j]>arr[j+1])
        {
            int tmp = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = tmp;
            /* code */
        }
    }
   }
}
void test(){
    int arr[]={9,8,7,6,4,5,3,2,1};
    int sz = sizeof(arr)/sizeof(arr[0]);
    buble(arr,sz);
    print_arr(arr,sz);
}
int main(){
 test();
}

冒泡函数的外层控制循环次数,一共n个数字比大小,每次找出一个最大的,当第n-1次找完之后,就只剩一下一个最小元素了,所以控制外层循环为n-1次。内存循环控制两个相邻数字的大小,因为使用arr[j]和arr[j+1]进行比较,所以要防止下标溢出。内层循环为j

2.调整参数,使函数可排序的选择更多

void swap(const void *e1,const void *e2,size_t size){
      char *p1=(char*)e1;
      char *p2=(char*)e2;
      for (int i = 0; i < size; i++)
      {
        char tmp=p1[i];
        p1[i]=p2[i];
        p2[i]=tmp;
      }
      
}
void buble_sort(void *base,size_t num,size_t size,int(*cmp)(const void *e1,const void *e2)){
 char *basec=(char*)base;
 for (int i = 0; i < num-1; i++)
   {
    for (int j = 0; j < num-1-i; j++)
    {
        if (cmp(basec+j*size,basec+(j+1)*size)>0)
        {
            swap(basec+j*size,basec+(j+1)*size,size);
            /* code */
        }
    }
   }
}

更改buble_sort函数的参数,要想对多种数据进行排序,数组的地址需要使用void*来接收,然后通过参数size可以知道每个元素所占的字节大小,将void*转化为char*。就可以算出要操作的元素的地址,swap函数也需要传入两个地址,同样用void指针接收,然后获得每个元素的字节数,一个字节一个字节的交换,最后就可以成功交换。

3.通过年龄排序结构体

struct  stus
{
    char name[20];
    int age;
};
void print_stus(struct stus *stu,int sz){
   for (int i = 0; i < sz; i++)
   {
    printf("%s-%d ",(stu+i)->name,(stu+i)->age);
   }
   printf("\n");
}
int cmp_age(const void *e1,const void *e2){
          return ((struct stus*)e1)->age-((struct stus*)e2)->age;
}
void test3(){
    struct stus stu[]={{"zhangsan",20},{"lisi",30},{"wangwu",15}};
     int sz = sizeof(stu)/sizeof(stu[0]);
     buble_sort(stu,sz,sizeof(stu[0]),cmp_age);
      print_stus(stu,sz);
}
int main(){
    test3();
    return 0;
}
//buble_sort同上

需要重写排序规则

4.通过姓名排序

int cmp_name(const void *e1,const void *e2){
    return strcmp(((struct stus*)e1)->name,((struct stus*)e2)->name);
}

只需创建排序函数将参数传入即可

你可能感兴趣的:(算法,c语言,学习)