起泡法排序

起泡法的思路是:将相邻的两个数比较,将小的调到前头。

可以推知,如果有 n 个数,则要进行 (n-1) 轮比较和交换。在第一轮要进行 (n-1) 次两两比较,在 j 轮中要进行 (n-j) 次两两比较。

下面将10个数从小到大进行排序:

#include<iostream>
using namespace std;
int main() {
	int a[11];
	int i, j, t;
	cout<<"input 10 numbers:\n";
	for (i=1; i<11; i++) {
		cin>>a[i];
	}
	cout<<endl;
	for (j=1; j<=9; j++) {
		for(i=1; i<=10-j; i++) {
			if (a[i] > a[i+1]) {
				t = a[i];
				a[i] = a[i+1];
				a[i+1] = t;
			}
		}
	}
	cout<<"the sorted numbers: \n";
	for (i=1; i<11; i++) {
		cout<<a[i]<<endl;
	}
	cout<<endl;
	return 0;
}

 

posted on 2014-11-28 13:32  humingX  阅读(1214)  评论(1编辑  收藏  举报

导航