模板:swp函数是用来交换数组里面的两个元素,Quicksort_low函数,将数组进行从小到大排序
Quicksort_high函数,将数组进行从大到小排序
以下是实现题目要求的代码:
#include "iostream"
using namespace std;
template<class T> void swp(T& a, T& b)
{
T temp;
temp = a;
a = b;
b = temp;
}
template <class T> void Quicksort_low(T* a, int l, int r) {
if (l >= r) return;
int i = l, j = r;
int key = l;
while (j > i) {
while (j > i && a[j] >= a[key])
j--;
while (j > i && a[i] <= a[key])
i++;
/*int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;*/
swp(a[i], a[j]);
}
/*int temp;
temp = a[key];
a[key] = a[i];
a[i] = temp;*/
swp(a[i], a[key]);
Quicksort_low(a, l, i - 1), Quicksort_low(a, i + 1, r);
}
template <class T> void Quicksort_high(T* a, int l, int r) {
if (l >= r) return;
int i = l, j = r;
int key = l;
while (j > i) {
while (j > i && a[j] <= a[key])
j--;
while (j > i && a[i] >= a[key])
i++;
/*int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;*/
swp(a[i], a[j]);
}
/*int temp;
temp = a[key];
a[key] = a[i];
a[i] = temp;*/
swp(a[i], a[key]);
Quicksort_high(a, l, i - 1), Quicksort_high(a, i + 1, r);
}
template<class T> void sort(T* a, int n, bool f)
{
if (f == 1)//从小到大排序
{
Quicksort_low(a, 0, n-1);
}
if (f == 0)//从大到小排序
{
Quicksort_high(a, 0, n-1);
}
}
int main()
{
int arr[5] = { 3,1,2,6,5 };
sort(arr, 5, 1);
cout << "排序后:" << endl;
for (int i = 0; i < 5; i++)
{
cout << arr[i] << endl;
}
return 0;
}