八大排序之快速排序

#include <iostream>

using namespace std;

template <class T>
void QuickSort(T* numbers, int low, int high);

int main()
{
    int low = 0, high = 0;
    cin >> low >> high;

    int data[100] = { 0 };
    for (int i = low; i <= high; ++i)
        cin >> data[i];

    QuickSort(data, low, high);

    for (int i = low; i <= high; ++i)
        cout << data[i] << " ";
    cout << endl;

    system("pause");
    return 0;
}

template <class T>
void QuickSort(T* numbers, int low, int high)
{
    if (numbers == NULL)//此處不要判斷low<0和high>0等條件,否則出錯
    {
        cout << "Error: invalid input!" << endl;
        return;
    }
    if (low >= high) return;//函數結束條件,必須要有

    int left = low, right = high;
    T pivot = numbers[left];

    while (left < right)
    {
        while (left < right && numbers[right] >= pivot)
        {
            --right;
        }   
        numbers[left] = numbers[right];

        while (left < right && numbers[left] <= pivot)
        {
            ++left;
        }
        numbers[right] = numbers[left];
    }
    numbers[left] = pivot;

    QuickSort(numbers, low, left - 1);
    QuickSort(numbers, left + 1, high);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章