场景
- 冒泡排序是简单的算法, 但是还是有些花样的
- 原理: 单趟扫描交换使最后一个元素永远是最大的, 扫描知到不需要发生交换
- 花样: 单趟扫描算法返回true表示剩下元素都是排过序的, 不需要继续循环
算法主体
// 单趟扫描交换算法主体算法
template<typename T>
bool bubble(T &numbers, RANK low, RANK high) {
bool sort = true;
while (++low < high) {
if (numbers[low - 1] > numbers[low]) {
sort = false;
swap(numbers[low], numbers[low - 1]);
}
}
return sort;
};
// 冒泡排序 [low, high)之间的元素进行排序
template<typename T>
vector<T> bubbleSort(vector<T> numbers, RANK low, RANK high) {
if (low < 0 || low > high || high > numbers.size()) {
throw new exception();
}
while (!bubble(numbers, low, high--));
return numbers;
};
运行例子
#include <iostream>
#include <vector>
using namespace std;
typedef int RANK;
typedef int T;
#define AGE_MIN 15
#define AGE_MAX 25
#define AGE_SIZE 10
#define STATUS_ERROR -1
// 15 25之间的年龄
RANK getRandomAges() {
return AGE_MIN + rand() % (AGE_MAX - AGE_MIN);
}
// 打印向量
void showAges(vector<T> ages) {
for (int i = 0; i < ages.size(); ++i) {
cout << " ages[" << i << "]=" << ages[i] << endl;
}
cout << "向量打印结束" << endl;
};
// 单趟扫描交换算法主体算法
template<typename T>
bool bubble(T &numbers, RANK low, RANK high) {
bool sort = true;
while (++low < high) {
if (numbers[low - 1] > numbers[low]) {
sort = false;
swap(numbers[low], numbers[low - 1]);
}
}
return sort;
};
// 冒泡排序 [low, high)之间的元素进行排序
template<typename T>
vector<T> bubbleSort(vector<T> numbers, RANK low, RANK high) {
if (low < 0 || low > high || high > numbers.size()) {
throw new exception();
}
while (!bubble(numbers, low, high--));
return numbers;
};
// 输出字符串
void print(string message) {
cout << message << endl;
}
int main() {
vector<RANK> ages;
for (int i = 0; i < AGE_SIZE; ++i) {
ages.push_back(getRandomAges());
}
showAges(ages);
print("开始排序");
ages = bubbleSort(ages, 0, ages.size());
print("结束排序");
showAges(ages);
return 0;
}
来源:CSDN
作者:cominglately
链接:https://blog.csdn.net/cominglately/article/details/103949298