川子767 2022-09-05 16:55 采纳率: 60%
浏览 30
已结题

模拟实现qsort函数,整型数组元素排序为什么是乱序呢

#include<stdio.h>
#include<string.h>
void Swap(char* buf1,char* buf2,int width)
{
    int i=0;
    for(i=0;i<width;i++)
    {
        char temp=*buf1;
        *buf1=*buf2;
        *buf2=temp;
        buf1++;
        buf2++;
    }
}
int cmp_int( void*e1, void* e2)
{
    return *(int*)e1-*(int*)e2;
}

void bubble_sort(void* base,int sz,int width,int(*cmp)(void*e1,void*e2))
{
    int i=0;
    for(i=0;i<sz-1;i++)
    {
        int j=0;
        for(j=0;j<sz-1-i;j++)
        {
            if(cmp((char*)base+j*width,(char*)base+(j+i)*width)>0)
            {
                Swap((char*)base+j*width,(char*)base+(j+1)*width,width);
            }
        }
    }
}
void test1()
{
    int arr[10]={9,8,7,6,5,4,3,2,1,0};
    int sz=sizeof(arr)/sizeof(arr[0]);
    bubble_sort(arr,sz,sizeof(arr[0]),cmp_int);
    int i=0;
    for(i=0;i<sz;i++)
    {
        printf("%d ",arr[i]);
    }
}
int main()
{
    //test();
    test1();
    return 0;
}

错误的输出结果:2 4 5 6 7 3 8 1 9 0

  • 写回答

3条回答 默认 最新

  • Huppert 2022-09-05 17:32
    关注

    第28行 j+i 应为 j+1,打错了吧

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 9月5日
  • 已采纳回答 9月5日
  • 修改了问题 9月5日
  • 创建了问题 9月5日

悬赏问题

  • ¥15 用lstm来预测股票价格
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上