C语言实现冒泡排序

这一生的挚爱 提交于 2019-12-06 00:12:37
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main()
{
    int score[] = {1, 2, 3, 4, 5, 7, 6};
    printf("before sort: ");
    for(int i=0;i < 7;i++)
    {
        printf("%d ", score[i]);
    }
    int sortTimes = BubbleSort(score, 7);
    printf("\nafter sort: ");
    for(int i=0;i < 7;i++)
    {
        printf("%d ", score[i]);
    }
    printf("\nsortTimes: %d", sortTimes);
    return 0;
}

int BubbleSort(int score[], int n)
{
    int sortTimes=0,temp;
    bool sorted = false;
    for(int i=0;i < n-1;i++)
    {
        sorted = false;
        for(int j=0;j < n-i-1;j++)
        {
            if(score[j] > score[j+1])
            {
                temp = score[j+1];
                score[j+1] = score[j];
                score[j] = temp;
                sortTimes++;
                sorted = true;
            }
        }
        if(!sorted)
            break;
    }
    return sortTimes;
}

注:

  1. C99中没有特定的布尔类型,因此引入<stdbool.h>使用bool类型
  2. 当在一遍二层循环中没有发生交换时,说明排序已经完成,直接结束循环
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!