要点:
1、冒泡排序就是从水底(数组尾部),把小的重量轻的,往水面上浮(移到数组头部)
2、从尾部开始,两两比较,若后一个比前一个小,则交换位置。
#include <iostream>
using namespace std;
template <typename T>
static void Swap(T& a, T& b)
{
T c(a);
a = b;
b = c;
}
//bubble
template <typename T>
static void Bubble(T array[], int len, bool min2max = true)
{
for(int i = 0; i<len; i++)
{
for(int j = len-1; j>i; j--)
{
if(min2max ? (array[j]<array[j-1]) : (array[j] > array[j-1]))
{
Swap(array[j], array[j-1]);
}
}
}
}
int main()
{
int array[] = {9,7,2,4,3,4,6,5,8,9};
Bubble(array, 10, true);
for(int i=0; i<10; i++)
{
cout << array[i] << endl;
}
cout << endl;
Bubble(array, 10, false);
for(int i=0; i<10; i++)
{
cout << array[i] << endl;
}
return 0;
}
2万+

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



