#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
template<typename T>
void quicksort(T data[], int first, int last) //快速排序开始
{
int lower = first + 1; //卫兵i
int upper = last; //卫兵j
//swap(data[first], data[(first + last) / 2]);
T bound = data[first]; //指定第一个节点
while (lower <= upper)
{
while (data[upper] > bound) //卫兵j先出动
upper--;
while (data[lower] < bound) //卫兵i后出动
lower++;
if (lower < upper) //左找大右找小,找到后换个位置
swap(data[lower++], data[upper--]);
else lower++; //卫兵碰面
}
swap(data[upper], data[first]); //将第一个节点和碰面节点换位置
if (first < upper - 1)
quicksort(data, first, upper - 1); //左边进行快速排序
if (upper + 1 < last)
quicksort(data, upper + 1, last); //右边进行快速排序
}
template<class T>
void quicksort(T data[], int n)
{
int i, max; //找出最大值,将最大值换到右边,如果
if (n < 2) //省略此步骤,则卫兵j必须先于卫兵i行
return; //动,防止i找不到最大值跑出地球
for (i = 1, max = 0; i < n; i++)
if (data[max] < data[i])
max = i;
swap(data[n - 1], data[max]);
quicksort(data, 0, n - 2); //开始快速排序
}
void PrintArray(int array[], int len)
{
for (int i = 0; i < len; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
int main(void)
{
const int NUM = 10;
int array[NUM] = { 0 };
srand((unsigned int)time(nullptr)); //种下种子防止随机数相同
for (int i = 0; i < NUM; i++) //生成随机数
{
array[i] = rand() % 100 + 1;
}
cout << "排序前:" << endl;
PrintArray(array, NUM);
cout << "排序后:" << endl;
quicksort(array, 0, NUM - 1); //开始快速排序
PrintArray(array, NUM);
return 0;
}
用C++模板实现快速排序算法
最新推荐文章于 2024-03-28 19:05:50 发布