冒泡排序,最多有n-1趟排序,每次比較n-1次,平均複雜度O(n^2),每趟排序都對鄰近元素進行比較。
#include <iostream>
using namespace std;
template <class T>
void BubbleSort(T* a, int n) {
int i;
bool flag;
T temp;
for (int i = 0; i < n-1; i++)
{
flag = true;
cout << " " << i << " ";
for (int j = 0; j < n - 1; j++) {
if (a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
flag = false;
}
}
for (int in = 0; in < n; in++)
{
cout << " " << a[in];
}
cout << endl;
if (flag)
{
break;
}
}
}
int main(int argc, const char* argv[]) {
int* a = new int[7];
a[0] = 2;
a[1] = 0;
a[2] = 3;
a[3] = 1;
a[4] = 7;
a[5] = 8;
a[6] = 4;
// BinaryInsertSortUp(a, 6);
// BinaryInsertSortDown(a, 6);
// SimpleSelectSortUp(a, 6);
BubbleSort(a, 7);
return 0;
}