冒泡排序是一种流行但低效的排序算法,第一次循环将最小的数放在数组第一位,第二次循环将次最小数放在数组第二位…
伪代码
C++代码
#include <iostream>
using namespace std;
void bubbleSort(int array[],int len);
int main()
{
int Array[]={ 2, 1, 5, 7, 3, 4, 8, 6 };
int length=sizeof (Array)/sizeof Array[0];
cout << "Before sorted:" << endl;
for(int i = 0;i < length;++i)
cout << Array[i] << " ";
cout << endl;
bubbleSort(Array,length);
cout << "After sorted:" << endl;
for(int i = 0;i < length;++i)
cout << Array[i] << " ";
cout << endl;
return 0;
}
void bubbleSort(int array[],int len)
{
int temp;
for(int i=0;i<len-1;++i)
{
for(int j=len-1;j>=i+1;--j)
{
if(array[j]<array[j-1])
{
temp=array[j];
array[j]=array[j-1];
array[j-1]=temp;
}
}
}
}
运行结果