基本冒泡排序: #include <iostream> #include <string> #include <stdlib.h> using namespace std; void swap(int &a,int &b); int main() { const int num = 5; int str[num]; cout<<"原数组:"; for(int i = 0;i<num;i++) { str[i] = num - i; cout<<str[i]<<" "; } cout<<endl; for(int i = 0;i<num-1;i++) { for(int j = 0;j <num-1-i;j++) { if(str[j]>str[j+1]) swap(str[j],str[j+1]); } cout<<"第"<<i+1<<"次排序后:"; for(int k = 0;k<num;k++) { cout<<str[k]<<" "; } cout<<endl; } cout<<"最终结果为:"; for(int i = 0;i<num;i++) { cout<<str[i]<<" "; } cout<<endl; system("pause"); return 0; } void swap(int &a,int &b) { int tmp; tmp = a; a = b; b = tmp; }
第一种改进方法(设定标志位,来避免不必要的排序):
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void swap(int &a,int &b);
int main()
{
const int num = 5;
int str[num];
cout<<"原数组:";
for(int i = 0;i<num;i++)
{
str[i] = i;
cout<<str[i]<<" ";
}
cout<<endl;
int needSort = 1;
for(int i = 0;i<num-1 && needSort;i++)
{
needSort = 0;
for(int j = 0;j <num-1-i;j++)
{
if(str[j]>str[j+1]) {
swap(str[j],str[j+1]);
needSort = 1;
}
}
cout<<"第"<<i+1<<"次排序后:";
for(int k = 0;k<num;k++)
{
cout<<str[k]<<" ";
}
cout<<endl;
}
cout<<"最终结果为:";
for(int i = 0;i<num;i++)
{
cout<<str[i]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
void swap(int &a,int &b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
第二种改进方法(记录需要排序的位置):、
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void swap(int &a,int &b);
int main()
{
const int num = 5;
int str[num];
cout<<"请输入:";
for(int i = 0;i<num;i++)
{
cin>>str[i];
}
cout<<endl;
int loc = num -1;
while(loc > 0)
{
int k = 0;
for(int i = 0;i<loc;i++)
{
if (str[i]>str[i+1])
{
swap(str[i],str[i+1]);
k=i;
}
}
loc = k;
cout<<"loc 在"<<loc<<"的位置"<<",当前排序为";
for(int k = 0;k<num;k++)
{
cout<<str[k]<<" ";
}
cout<<endl;
}
cout<<"最终结果为:";
for(int i = 0;i<num;i++)
{
cout<<str[i]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
void swap(int &a,int &b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}