冒泡排序

//冒泡是相邻的两个数比较

void bubble_sort_low(int unsorted[], int count) //低级

{

    for (int i = 0; i< count-1; i++) { //比较的趟数

        printf("-----------------\n");

        for (int j=0; j<count-1-i; j++) {

            if (unsorted[j] > unsorted[j+1]) {

                swap(&unsorted[j], &unsorted[j+1]);

            }

        }

    }

}


//中级优化,设置一个标志,如果这一趟发生了交换,则为true,否则为false。明显如果有一趟没有发生交换,说明排序已经完成。

void bubble_sort_middle(int unsorted[], int count) //中级

{

    int flag = 1;

    int remaindCount = count;

    while (flag) {

        printf("-----------------\n");

        flag = 0;

        for (int j = 0; j < remaindCount-1; j++) {

            if (unsorted[j] > unsorted[j+1])

            {

                swap(&unsorted[j], &unsorted[j+1]);

                flag = 1;

            }

        }

        remaindCount--;

    }

}


//高级优化,如果有100个数的数组,仅前面10个无序,后面90个都已排好序且都大于前面10个数字,那么在第一趟遍历后,最后发生交换的位置必定小于10,且这个位置之后的数据必定已经有序了,记录下这位置,第二次只要从数组头部遍历到这个位置就可以了。

void bubble_sort_high(int unsorted[], int count) //高级 和中级次数相同,但时间短

{

    int remaindCount;

    int flag = count;

    while (flag > 0) {

        printf("-----------------\n");

        remaindCount = flag;

        flag = 0;

        for (int j = 0; j < remaindCount-1; j++) {

            if (unsorted[j] > unsorted[j+1]) {

                swap(&unsorted[j], &unsorted[j+1]);

                flag = j+1;

            }

        }

    }

}


int main(int argc, const char * argv[])

{

    int x[] = { 6, 2, 4, 1, 5, 3, 7, 8, 9, 10, 11};

    //bubble_sort_low(x, 11);

    bubble_sort_middle(x, 11);

    //bubble_sort_high(x, 11);


    for (int index = 0; index<11; index++) {

        printf("%d ",x[index]);

    }

    printf("\n");


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值