</pre><pre name="code" class="cpp">/**
* C++ code
* 二元冒泡
* 20150905
* yansifang
*/
#include<cstdio>
#include<iostream>
using namespace std;
/**
*打印输出数组元素
*/
void Print(int a[],int n)
{
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
/**
*交换两数
*/
void Swap(int &a,int &b)
{
a=a+b;
b=a-b;
a=a-b;
}
/**
*二元冒泡
@low 记录每趟反向冒泡最后一次交换的位置
@lowPos 记录每趟反向冒泡每次交换的位置(临时存储变量)
@high 记录每趟正向冒泡最后一次交换的位置
@highPos 记录每趟正向冒泡每次交换的位置(临时存储变量)
*/
void BubbleSort_2(int a[],int n)
{
int low,high,lowPos,highPos;
low=0;
high=n-1;
while(low<high)
{
//最大数往后冒
highPos=low; //每趟正向开始前交换位置为初始化为low
for(int i=low;i<high;i++)
{
if(a[i]>a[i+1])
{
Swap(a[i],a[i+1]);
highPos=i;
}
}
high=highPos;
//最小数往前冒
lowPos=high; //每趟反向开始前交换位置为初始化为high
for(int j=high;j>low;j--)
{
if(a[j]<a[j-1])
{
Swap(a[j],a[j-1]);
lowPos=j;
}
}
low=lowPos;
}
}
int main()
{
int a[]={5,1,2,3,4};
cout<<"排序前:";
Print(a,5);
cout<<"排序后";
BubbleSort_2(a,5);
Print(a,5);
getchar();
}
运行结果二元冒泡排序(改进的冒泡算法)
最新推荐文章于 2020-02-14 21:06:53 发布