排序过程:
将第一个记录的keyword与第二个记录的keyword进行比較,若为逆序r[1].key > r[2].key,则交换;然后比較第二个记录与第三个记录;依次类推,直至第n - 1个记录和第n个记录比較为止,第一趟冒泡排序,结果keyword最大的记录被安置在最后一个记录上。
对前n - 1个记录进行第二趟冒泡排序。结果使keyword次大的记录被安置在第n - 1个记录位置。
反复上述过程,直到“在一趟排序过程中没有进行过交换记录的操作”为止。
时间复杂度O(n^2)
简单版:
#include <iostream>
#include <cstdio>
#include <ctime>
#include <iomanip>
using namespace std;
int arr[10000];
void mySwap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}
void bubbleSort(int *a, int len)
{
bool alreadySort = false; // 记录假设已经排序完毕,能够提前退出
for (int i = len - 1; i >= 0 && !alreadySort; i--) { // 从后往前排序
alreadySort = true;
for (int j = 0; j < i; j++) {
if (a[j] > a[j + 1]) {
mySwap(a[j], a[j + 1]);
alreadySort = false;
}
}
}
}
void printArray(int *a, int len)
{
for (int i = 0; i < len; i++) {
if (i != 0 && i % 10 == 0) {
cout << endl;
}
cout << setw(3) << a[i] << ' ';
}
cout << endl;
}
int main()
{
srand(time(0));
cout << "Please input length of array: ";
int len;
cin >> len;
for (int i = 0; i < len; i++) {
arr[i] = rand() % 100;
}
cout << "Before sorting:\n";
printArray(arr, len);
bubbleSort(arr, len);
cout << "After sorting:\n";
printArray(arr, len);
return 0;
}
/*
Please input length of array: 20
Before sorting:
70 53 65 69 99 67 36 49 66 16
58 73 65 20 75 30 93 8 42 57
After sorting:
8 16 20 30 36 42 49 53 57 58
65 65 66 67 69 70 73 75 93 99
*/
改进:记住最后一次交换发生的位置lastExchange,下一趟排序開始时,R[1...lastExchange]是无序区,R[lastExchange...n]是有序区。这样一趟排序可能使当前有序区扩充多个记录,从而降低排序的趟数。
仅仅需改进bublleSort函数:
void bubbleSort(int *a, int len)
{
bool alreadySort = false; // 记录假设已经排序完毕。能够提前退出
for (int i = len - 1; i >= 0 && !alreadySort;) { // 从后往前排序
alreadySort = true;
int lastExchange = i; // 记住最后一次交换的位置,能够降低排序趟数
for (int j = 0; j < i; j++) {
if (a[j] > a[j + 1]) {
mySwap(a[j], a[j + 1]);
alreadySort = false;
lastExchange = j;
}
}
i = (lastExchange < i ? lastExchange : i - 1);
}
}