您的位置:首页 > 编程语言 > C语言/C++

冒泡排序-c++代码实现及运行实例结果

2017-12-14 21:05 1176 查看
冒泡排序是一种流行但低效的排序算法,第一次循环将最小的数放在数组第一位,第二次循环将次最小数放在数组第二位…

伪代码



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;
}
}
}
}


运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: