详解冒泡排序
来源:互联网 发布:54坐标系数据 编辑:程序博客网 时间:2024/06/05 10:40
现有数组a[n]
思想: 将较小的数(或较大的数)前移;主要有两种求解方法,冒泡是从前半段还是从后半段开始
(1)基本
冒泡数组首部开始:
void BubbleSort(type a[],int n){int i,j;type temp;for(i=0;i<n;i++){ for(j=1;j<n-i;j++) { if(a[j-1]>a[j]) { temp=a[j]; a[j]=a[j-1]; a[j-1]=temp; } } }}冒泡从数组尾部开始:
//冒泡从后半段开始 基本冒泡排序void BubbleSort_1(type a[],int n){int i,j;type temp;for(i=0;i<n;i++){ for(j=n-1;j>i;j--) { if(a[j-1]>a[j]) { temp=a[j]; a[j]=a[j-1]; a[j-1]=temp; } }}}
(2)改进
设置一个标志,如果这一趟发生了交换,则为true,否则为false。明显如果有一趟没有发生交换,说明排序已经完成。
//冒泡排序改进方法1 冒泡从数组首部开始void BubbleSort1(type a[], int n){int i,j;type temp;bool flag; //交换标志位for(i=0;i<n;i++){ flag=false; for(j=1;j<n-i;j++) { if(a[j-1]>a[j]) { temp=a[j-1]; a[j-1]=a[j]; a[j]=temp; flag=true; } } if(!flag) //如果没有发生交换 说明已完成排序 return;}}//冒泡排序改进方法1 冒泡从数组尾部开始void BubbleSort1_1(type a[], int n){int i,j;type temp;bool flag; //交换标志位for(i=0;i<n;i++){ flag=false; for(j=n-1;j>i;j--) { if(a[j-1]>a[j]) { temp=a[j-1]; a[j-1]=a[j]; a[j]=temp; flag=true; } } if(!flag) //如果没有发生交换 说明已完成排序 return;}}
(3)改进2
记录一次冒泡后最后交换的位置
代码如下:
//冒泡排序改进2 记录最后发生交换的记录 冒泡从数组首部开始 void BubbleSort2(int a[], int n){ int i,j;type temp;int flag; //最后一次交换的位置 flag=0;for(i=0;i<n;i++){ for(j=1;j<n-flag;j++) { if(a[j-1]<a[j]) { temp=a[j-1]; a[j-1]=a[j]; a[j]=temp; } } flag=j-1;}}//冒泡排序改进2 记录最后发生交换的记录 冒泡从数组尾部开始 void BubbleSort2_1(int a[], int n){ int i,j;type temp;int flag; //最后一次交换的位置 flag=0;for(i=0;i<n;i++){ for(j=n-1;j>flag;j--) { if(a[j-1]>a[j]) { temp=a[j-1]; a[j-1]=a[j]; a[j]=temp; } } flag=j+1;}}
参考来源: MoreWindows 博客 http://blog.csdn.net/morewindows/article/details/6657829
0 0
- 排序详解:冒泡排序
- 冒泡排序(bubble_sort)详解
- 冒泡排序详解
- PHP冒泡排序详解
- 冒泡排序详解
- 冒泡排序原理详解
- 详解冒泡排序
- 冒泡排序深入详解
- 冒泡排序代码详解
- 冒泡排序算法详解
- 【17】-冒泡排序详解
- 冒泡排序详解
- java冒泡排序详解
- 冒泡排序详解
- 冒泡排序详解
- 冒泡排序算法详解
- 冒泡排序详解
- 冒泡排序详解
- html标签SEO规范
- 图像去模糊之初探--Single Image Motion Deblurring
- Mysql从外部文件导入数据
- 关于apk文件的反编译与防反编译
- 使用DNSCrypt解决DNS污染问题
- 详解冒泡排序
- [Sprincglib] spring aop报错:Cannot proxy target class because CGLIB2 is not available.
- 蜗牛—Android基础之简易猜拳游戏
- 64_leetcode_reverse Linked List II
- 女子与丈夫发生矛盾后想不开溺水身亡-中国吉林网
- EL表达式总结
- 黑马程序员--IO流
- Prefix.pch文件的作用
- mysql 创建用户失败