1、算法说明
假设:有n个元素的数组array[n-1],未进行排序,现要求从小到大进行排序。
第一轮:从下标0和1开始,将相邻的两个元素(数字)进行比较,如果不满足要求则交换,直至比较并排序最后两个元素(array[n-2]与arra[n-1])为止。
第二轮:从下标0和1开始,将相邻的两个元素(数字)进行比较,如果不满足要求则交换,直至比较并排序array[n-2]与array[n-1]元素为止。
...
最后一轮(第n-1轮):比较array[0]与array[1]两个元素并排序。
2、代码
#include <iostream>
using namespace std;
#define debug 1
void sort_bubble(int *array, int len);
void swap(int *pa, int *pb);
void output(int *array, int len);
int main(int argc, char *argv[])
{
int num = 0;
cout << "Please input an integer." << endl;
cin >> num;
if(num <= 0) return 0;
int array[num];
cout << "Please input " << num << " integers." << endl;
for(int i = 0; i < num; i++) cin >> array[i];
if(debug) {
cout << "Before sorting, the numbers are as following:" << endl;
output(array, num);
}
sort_bubble(array, num);
if(debug) cout << "After sorting, the numbers are as following:" << endl;
output(array, num);
return 0;
}
/***************************************
Function: sort_bubble
Arguments:
array: pointer to an array of integers.
len: length of the array.
Algorithm:
Compare the next two integers and swap if necessary each time.
Put the maximum number to the last after first round.
***************************************/
void sort_bubble(int *array, int len)
{
if(!array || len <= 0) return;
for(int i = 0; i < len - 1; i++) {
for(int j = 0; j < len - 1 - i; j++) {
if(debug) {
cout << j << ", " << j + 1 << ": ";
output(array, len);
}
if(array[j] > array[j + 1]) {
swap(&array[j], &array[j + 1]);
if(debug) {
cout << j << ", " << j + 1 << ": ";
output(array, len);
}
}
}
}
}
void swap(int *pa, int *pb)
{
if(!pa || !pb) return;
int t = *pa;
*pa = *pb;
*pb = t;
}
void output(int *array, int len)
{
if(!array || len <= 0) return;
for(int i = 0; i < len; i++) cout << array[i] << " ";
cout << endl;
}
3、调试说明
需要查看具体排序过程:
#define debug 1
不需要查看具体排序过程:
#define debug 0
4、运行结果
输入:
5
5 4 3 2 1
输出:
Please input an integer.
Please input 5 integers.
Before sorting, the numbers are as following:
5 4 3 2 1
0, 1: 5 4 3 2 1
0, 1: 4 5 3 2 1
1, 2: 4 5 3 2 1
1, 2: 4 3 5 2 1
2, 3: 4 3 5 2 1
2, 3: 4 3 2 5 1
3, 4: 4 3 2 5 1
3, 4: 4 3 2 1 5
0, 1: 4 3 2 1 5
0, 1: 3 4 2 1 5
1, 2: 3 4 2 1 5
1, 2: 3 2 4 1 5
2, 3: 3 2 4 1 5
2, 3: 3 2 1 4 5
0, 1: 3 2 1 4 5
0, 1: 2 3 1 4 5
1, 2: 2 3 1 4 5
1, 2: 2 1 3 4 5
0, 1: 2 1 3 4 5
0, 1: 1 2 3 4 5
After sorting, the numbers are as following:
1 2 3 4 5