关于冒泡法~~~
看了冒泡法的思想,自己试编个,结果没有输出结果 这是怎么一回事呢?
- C/C++ code
#include <iostream>using namespace std;int main(){ int a[5]={5,1,2,9,8}; //5个元素,计算4次 int temp; for(int i=1;i<5;i++) { for(int j=4;j>=i;j--) { if(a[j]<a[j-1]) { temp = a[j-1]; a[j-1] = a[j]; a[j] = temp; } } } for(int k=0;i<5;i++) { cout<<a[k]<<" "; } cout<<endl; return 0;}}[解决办法]
#include <iostream>
using namespace std;
int main()
{
int a[5]={5,1,2,9,8}; //5个元素,计算4次
int temp;
for(int i=0;i<5;i++)
{
for(int j=0;j<5-1-j;j++)
{
if(a[j]>a[j+1])
{
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
}
}
for(int k=0;k<5;k++)
{
cout<<a[k]<<" ";
}
cout<<endl;
return 0;
}