cpp-interview/Algorithm/BubbleSort_orderly.h

14 lines
360 B
C
Raw Normal View History

2018-02-11 00:20:34 +08:00
// 冒泡排序(改进版)
2018-02-09 21:47:58 +08:00
void BubbleSort_orderly(vector<int>& v) {
2018-03-28 13:06:39 +08:00
int len = v.size();
2018-02-09 21:47:58 +08:00
bool orderly = false;
2018-03-28 13:06:39 +08:00
for (int i = 0; i < len - 1 && !orderly; ++i) {
2018-02-09 21:47:58 +08:00
orderly = true;
2018-03-28 13:06:39 +08:00
for (int j = 0; j < len - 1 - i; ++j) {
2018-02-11 00:20:34 +08:00
if (v[j] > v[j + 1]) { // 从小到大
orderly = false; // 发生交换则仍非有序
2018-03-28 13:06:39 +08:00
swap(v[j], v[j + 1]);
2018-02-09 21:47:58 +08:00
}
}
}
}