冒泡排序,是比较相邻的两个元素,关键字小的往数组头移动,连续比较所有的相邻元素,最终实现数组的有序排序。这个非常简单。就不多解释了。
#include<iostream>
using namespace std;
void swap(int & i , int & j) {
int temp;
temp = i;
i = j;
j = temp;
}
void bubbleSortBasic(int a[], int length , int & compare , int & move) {
compare = move = 0;
for(int i = 0 ; i < length - 1 ; i++)
for (int j = i + 1; j < length; j++) {
compare++;
if (a[i] > a[j]) {
move++;
swap(a[i],a[j]);
}
}
for (int i = 0; i < length; i++)
cout << a[i] << ' ';
cout << endl << "compare times :" << compare << " , move times : " <<
move * 3<< endl;
}
void bubbleSortTypical(int a[], int length, int& compare, int& move) {
compare = move = 0;
for (int i = 0; i < length - 1; i++)
for (int j = length - 1; j > i; j--) {
compare++;
if (a[j] < a[j - 1]) {
move++;
swap(a[j - 1], a[j]);
}
}
for (int i = 0; i < length; i++)
cout << a[i] << ' ';
cout << endl << "compare times :" << compare << " , move times : " <<
move * 3 << endl;
}
void bubbleSortBest(int a[], int length, int& compare, int& move) {
bool sorted = false;//true 表示已经排好了序,false表示乱序
compare = move = 0;
for (int i = 0; i < length - 1 && !sorted; i++) {
sorted = true;
for (int j = length - 1; j > i; j--) {
compare++;
if (a[j] < a[j - 1]) {
move++;
swap(a[j - 1], a[j]);
sorted = false;
}
}
}
for (int i = 0; i < length; i++)
cout << a[i] << ' ';
cout << endl << "compare times :" << compare << " , move times : " <<
move * 3 << endl;
}
int main() {
int a[] = { 1,0,2,3,4,5,6,7,8,9 }, length = 10;
int b[] = { 1,0,2,3,4,5,6,7,8,9 };
int c[] = { 1,0,2,3,4,5,6,7,8,9 };
int compare, move;
bubbleSortBasic(a,length,compare,move);
cout << endl;
bubbleSortTypical(b, length, compare, move);
cout << endl;
bubbleSortBest(c, length, compare, move);
}
测试结果如下:

谢谢阅读
本文介绍了冒泡排序的基本原理,展示了三种不同优化版本的冒泡排序算法:基本版、典型版和最佳情况版,并通过代码实现进行了详细解释。在每个版本中,都记录了比较和交换次数,以展示其效率差异。测试结果显示了各种排序方法在相同数据集上的执行效果。
2579

被折叠的 条评论
为什么被折叠?



