2025年3月13日 星期四 甲辰(龙)年 月十二 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言使用冒泡排序将整数数组内的元素正序排列

时间:01-03来源:作者:点击数:54

下面的程序将会读入一个整数数组,然后使用冒泡排序法将数组内的元素正序(从小到大)排列。

关于冒泡排序请查看:C语言冒泡排序算法及代码

注意:下面的程序在 VC6.0 下编译不能通过,因为在 VC6.0 中数组长度不能为变量和不定值;请在 Linux 的 GCC 或 Window 的 MinGW 下编译。

笔者顺便推荐一款国产C语言开发神器 -- C-Free 5.0 -- 默认编译器是 MinGW,可以随意切换多个编译器,详情请查看:C-Free 5.0下载[带注册码][赠送破解版][最性感的C、C++开发工具IDE]

  • #include <stdio.h>
  • #define NMAX 10
  • int getIntArray(int a[], int nmax, int sentinel);
  • void printIntArray(int a[], int n);
  • void bubbleSort(int a[], int n);
  • int main(void) {
  • int x[NMAX];
  • int hmny;
  • int who;
  • int where;
  • hmny = getIntArray(x, NMAX, 0);
  • if (hmny==0)
  • printf("This is the empty array!\n");
  • else{
  • printf("The array was: \n");
  • printIntArray(x,hmny);
  • bubbleSort(x,hmny);
  • printf("The sorted array is: \n");
  • printIntArray(x,hmny);
  • }
  • }
  • // n 是数组 a 的元素个数;数组内的元素将会输出,5 个一行
  • void printIntArray(int a[], int n)
  • {
  • int i;
  • for (i=0; i<n; ){
  • printf("\t%d ", a[i++]);
  • if (i%5==0)
  • printf("\n");
  • }
  • printf("\n");
  • }
  • // 最多读入 nmax 个整数并保存到数组 a,遇到特定值结束读取
  • int getIntArray(int a[], int nmax, int sentinel)
  • {
  • int n = 0;
  • int temp;
  • do {
  • printf("Enter integer [%d to terminate] : ", sentinel);
  • scanf("%d", &temp);
  • if (temp==sentinel) break;
  • if (n==nmax)
  • printf("array is full\n");
  • else
  • a[n++] = temp;
  • }while (1);
  • return n;
  • }
  • // 该函数使用冒泡排序将数组 a 中前 n 个元素正序排列
  • void bubbleSort(int a[], int n)
  • {
  • int lcv;
  • int limit = n-1;
  • int temp;
  • int lastChange;
  • while (limit) {
  • lastChange = 0;
  • for (lcv=0;lcv<limit;lcv++)
  • if (a[lcv]>a[lcv+1]) {
  • temp = a[lcv];
  • a[lcv] = a[lcv+1];
  • a[lcv+1] = temp;
  • lastChange = lcv;
  • }
  • limit = lastChange;
  • }
  • }

可能的输出结果:

Enter integer [0 to terminate] : 1 45 232 56 343 12 3 0
The array was:
    1      45    232    56    343
    12    3
The sorted array is:
    1         3       12    45    56
    232    343
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门