标签:
QuickSort.h文件
#pragma once
/*交换两个数*/
template<class T>
void Swamp(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
/*
将数组分为小于等于x,和大于x的两个部分
其中这里x选择为数组的最后一个元素
如当输入{ 2,8,7,1,3,5,6,4 }时,输出为{2,1,3,4,7,5,6,8},函数返回值为3,即数组中x的索引
*/
template<class T>
int Partition(T *src,int startIndex,int endIndex)
{
T x = src[endIndex];
int i = startIndex - 1;
for (int j = startIndex; j < endIndex; j++) {
if (src[j] <= x) {
i++;
Swamp(src[i], src[j]);
}
}
Swamp(src[i + 1], src[endIndex]);
return i + 1;
}
/*
快速排序算法
对数组从startIndex-endIndex的元素进行排序
*/
template<class T>
void QuickSort(T *src, int startIndex,int endIndex)
{
if (startIndex < endIndex) {
int middleIndex = Partition(src, startIndex, endIndex); //以middleIndex为界排列成左右两部分
QuickSort(src, startIndex, middleIndex - 1); //递归调用排列左侧一部分
QuickSort(src, middleIndex + 1, endIndex); //递归调用排列右侧一部分
}
}
RandomQuickSort.h
#pragma once
#include<stdlib.h>
#include<math.h>
#include<time.h>
#include"QuickSort.h"
#define random(a,b) (((double)rand()/RAND_MAX)*(b-a)+a)
/*
产生一个[a,b]区间内的随机数*/
int Random(int a, int b)
{
double r = random(a, b);
return int(r > 0 ? floor(r + 0.5) : ceil(r - 0.5)); //四舍五入
}
/*
将数组分为小于等于x,和大于x的两个部分
其中这里x选择为数组的最后一个元素
如当输入{ 2,8,7,1,3,5,6,4 }时,输出为{2,1,3,4,7,5,6,8},函数返回值为3,即数组中x的索引
*/
template<class T>
int RandomPartition(T *src, int startIndex, int endIndex)
{
int i = Random(startIndex, endIndex);
Swamp(src[i], src[endIndex]);
return Partition(src,startIndex,endIndex);
}
/*
快速排序算法
对数组从startIndex-endIndex的元素进行排序
*/
template<class T>
void RandomQuickSort(T *src, int startIndex, int endIndex)
{
if (startIndex < endIndex) {
int middleIndex = RandomPartition(src, startIndex, endIndex); //以middleIndex为界排列成左右两部分
RandomQuickSort(src, startIndex, middleIndex - 1); //递归调用排列左侧一部分
RandomQuickSort(src, middleIndex + 1, endIndex); //递归调用排列右侧一部分
}
}
标签:
原文地址:http://www.cnblogs.com/ql698214/p/5424865.html