源代码 |
int main(){
int a[5]={7,2,-5,8,13};
int temp=0;
int i,j;
cout<<"Before:"<<endl;
for (i=0; i<5; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
for (i=0; i<5-1; i++) {
for (j=0; j<5-1-i; j++) {
if (a[j]>a[j+1]) {
temp=a[j];a[j]=a[j+1];a[j+1]=temp;
}
}
}
cout<<"After:"<<endl;
for (i=0; i<5; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
}
或者可以这样写
int main(){
int a[]={7,2,-5,8,13};
int temp=0;
int i,j;
cout<<"Before:"<<endl;
for (i=0; i<sizeof(a)/sizeof(int); i++) {
cout<<a[i]<<" ";
}
cout<<endl;
for (i=0; i<sizeof(a)/sizeof(int)-1; i++) {
for (j=0; j<sizeof(a)/sizeof(int)-1-i; j++) {
if (a[j]>a[j+1]) {
temp=a[j];a[j]=a[j+1];a[j+1]=temp;
}
}
}
cout<<"After:"<<endl;
for (i=0; i<sizeof(a)/sizeof(int); i++) {
cout<<a[i]<<" ";
}
cout<<endl;
}
sizeof(a)/sizeof(int)
表示求出数组有效长度。
运行结果如下
Before:
7 2 -5 8 13
After:
-5 2 7 8 13
核心代码 |
for (i=0; i<数组长度-1; i++) {
for (j=0; j<数组长度-1-i; j++) {
if (a[j]>a[j+1]) {
temp=a[j];a[j]=a[j+1];a[j+1]=temp;
}
}
}
冒泡排序法过程 |
说明 |
如果要排序从大到小,a[j]>a[j+1]
改成a[j]<a[j+1]
即可。
遇到相同的数字不会采用交换的方式!