C++ 冒泡排序 以及优化
原理:

代码实现:
#include <iostream>
using namespace std;
void swap( int& a,int& b )
{
int temp=a;
a=b;
b=temp;
}
//最基本的冒泡排序
void BubbleSort_01(int array[],int length)
{
for(int i=0;i<length;i++)
{
for(int j=0;j<length-i-1;j++)
{
if(array[j]>array[j+1])
{
swap(array[j],array[j+1]);
}
}
}
}
void BubbleSort_02(int array[],int length)
{
bool is_sorted=true;//记录数组是否已经有序,减少比较轮次
for(int i=0;i<length;i++)
{
for(int j=0;j<length-i-1;j++)
{
if(array[j]>array[j+1])
{
swap(array[j],array[j+1]);
is_sorted=false;
}
}
if(is_sorted)break;
}
}
//基于半有序数组的优化 eg: p[]={5 4 3 2 6 7 8 9}
void BubbleSort_03(int array[],int length)
{
bool is_sorted=true;
int unsorted_border=length-1;
int last_index=0;//记录无序数组的最右下标
for(int i=0;i<length;i++)
{
for(int j=0;j<unsorted_border;j++)
{
if(array[j]>array[j+1])
{
swap(array[j],array[j+1]);
is_sorted=false;
last_index=j;
}
}
unsorted_border=last_index;//更新无序数组边界,下一轮只比较到该下标位置
if(is_sorted)break;
}
}
int main()
{
cout << "please input the length of array:" << endl;
int n;
cin>>n;
int *p=new int[n];
cout << "please input the data of array:" << endl;
for(int i=0;i<n;i++)
cin>>p[i];
cout << "执行BubbleSort:" << endl;
BubbleSort_01(p,n);
for(int i=0;i<n;i++)
cout<<p[i]<<" ";
return 0;
}