首页 > 后端开发 > C++ > 正文

使用冒泡排序算法对给定的数字列表进行升序排序的C程序

王林
发布: 2023-09-23 13:01:02
转载
1907人浏览过

使用冒泡排序算法对给定的数字列表进行升序排序的c程序

在 C 编程语言中,冒泡排序是最简单的排序技术,也称为交换排序。

冒泡排序过程

  • 将第一个元素与列表中的其余元素进行比较,如果它们不按顺序进行交换(交换)。

  • 对列表中的其他元素重复相同的操作列表,直到所有元素都已排序。

算法

下面给出的是一种算法,通过使用冒泡排序技术 -

第 1 步 - 开始

第 2 步 - 获取列表(数组),num

第 3 步− readlist(list,num)

第 4 步− printlist(list,num)

第5步 - bub_sort(list,num)

第6步 - printlist(list,num)

readlist (list, num)
登录后复制

第7步 − 停止

1. for j = 0 to num
2. read list[j].
登录后复制

打印列表(列表,数字)

1. for j =0 to num
2. write list[j].
登录后复制

bub_sort(列表,数字)

1. for i = 0 to num
2. for j =0 to (num – i)
3. if( list[j] > list[j+1])
4. swapList( address of list[j], address of list[j+1])
登录后复制

swapList( list[j]的地址, list[j+1]的地址)

1. temp = value at list[j]
2. value at list[j] = value at list[j+1]
3. value at list[j+1] = temp
登录后复制

示例

以下是用冒泡排序技术对给定数字列表进行升序排序的C程序

 演示

#include <stdio.h>
#define MAX 10
void swapList(int *m,int *n){
   int temp;
   temp = *m;
   *m = *n;
   *n = temp;
}
/* Function for Bubble Sort */
void bub_sort(int list[], int n){
   int i,j;
   for(i=0;i<(n-1);i++)
      for(j=0;j<(n-(i+1));j++)
         if(list[j] > list[j+1])
            swapList(&list[j],&list[j+1]);
   }
   void readlist(int list[],int n){
   int j;
   printf("</p><p>Enter the elements: </p><p>");
   for(j=0;j<n;j++)
      scanf("%d",&list[j]);
   }
   /* Showing the contents of the list */
   void printlist(int list[],int n){
      int j;
   for(j=0;j<n;j++)
      printf("%d\t",list[j]);
}
void main(){
   int list[MAX], num;
   printf(" Enter the number of elements </p><p>");
   scanf("%d",&num);
   readlist(list,num);
   printf("</p><p></p><p>Elements in the list before sorting are:</p><p>");
   printlist(list,num);
   bub_sort(list,num);
   printf("</p><p></p><p>Elements in the list after sorting are:</p><p>");
   printlist(list,num);
}
登录后复制

输出

执行上述程序时,会产生以下结果 -

Enter the number of elements
10

Enter the elements:
11
23
45
1
3

6
35
69
10
22


Elements in the list before sorting are:
11 23 45 1 3 6 35 69 10 22

Elements in the list after sorting are:
1 3 6 10 11 22 23 35 45 69
登录后复制

以上就是使用冒泡排序算法对给定的数字列表进行升序排序的C程序的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号