菜鸟笔记
提升您的技术认知

c语言冒泡排序将一个数组按照从小到大进行排序-ag真人游戏

例如 int a[10] = {0,5,2,3,6,9,8,7,4,1}
对其10个整数由小到大进行排序
思想:冒泡排序

实现一:

#include
int main()
{
    int i = 0;
    int a[10] = {
  0,5,2,3,6,9,8,7,4,1};
    int j = 0;
    int tmp = 0;
    int m = sizeof(a) / sizeof(a[0]);  //s数组大小
    for (i=0; ia[j 1])    //如果a[j]比a[j 1]大则交换内容
            {
                tmp = a[j 1];
                a[j 1] = a[j];
                a[j] = tmp;
            }
        }
    }
    for (i=0; i < m; i  )
    {
        printf(" %d ", a[i]);   //打印
    }
    printf(" \n ");
    return 0;
}

实现二:
自定义sort函数

#include
void sort(int a[], int m)
{
    int i = 0;
    int j = 0;
    int tmp = 0;
    for (i = 0; ia[j   1])
            {
                tmp = a[j   1];
                a[j   1] = a[j];
                a[j] = tmp;
            }
        }
    }
}
int main()
{
    int i = 0;
    int a[10] = {
  0,5,2,3,6,9,8,7,4,1};
    int m = sizeof(a) / sizeof(a[0]);
    sort(a, m);
    for (i=0; i < m; i  )
    {
        printf(" %d ", a[i]);
    }
    printf(" \n ");
    return 0;
}
网站地图