冒泡排序,是比较相邻的两个元素,关键字小的往数组头移动,连续比较所有的相邻元素,最终实现数组的有序排序。这个非常简单。就不多解释了。
#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);
}
测试结果如下:
谢谢阅读