冒泡排序也可以寫出一些花樣

場景

  • 冒泡排序是簡單的算法, 但是還是有些花樣的
    • 原理: 單趟掃描交換使最後一個元素永遠是最大的, 掃描知到不需要發生交換
    • 花樣: 單趟掃描算法返回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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章