若有错误,诚请指正
quick_sort.h
/*-----------------------------------------------
Created By EverSteins
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/
#ifndef QUEUE_H
#define QUEUE_H
#include "utility.h"
typedef int ElemType;
class Sort
{
public:
static void QuickSort(ElemType *arr,const int n);
private:
static void QSort(ElemType *arr,int low,int high);
static int Partion(ElemType *arr,int low,int high);
static ElemType& Median3(ElemType *arr,int low,int high);
static void Swap(ElemType &e1,ElemType &e2);
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
DISALLOW_COPY_AND_ASSIGN(Sort);
#undef DISALLOW_COPY_AND_ASSIGN
};
#endif
quick_sort.cc
/*-----------------------------------------------
Created By EverSteins
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/
#include "stdafx.h"
#include <iostream>
#include "utility.h"
#include "quick_sort.h"
using namespace std;
void Sort::QuickSort(ElemType *arr,const int n)
{
//pre:n>=1
assert(n>=1);
QSort(arr,0,n-1);
}
void Sort::QSort(ElemType *arr,int low,int high)
{
//pre:high>low
if (high<=low)
return;
int pivot=Partion(arr,low,high);
QSort(arr,low,pivot-1);
QSort(arr,pivot+1,high);
}
int Sort::Partion(ElemType *arr,int low,int high)
{
//pre:high>low
ElemType pivot_key=Median3(arr,low,high);
while (low<high)
{
while (low<high && pivot_key<=arr[high]) //注意这里不是<
--high;
arr[low]=arr[high];
while (low<high && arr[low]<=pivot_key) //注意这里不是>
++low;
arr[high]=arr[low];
}
arr[low]=pivot_key;
return low;
}
ElemType& Sort::Median3(ElemType *arr,int low,int high)
{
//summary:置low为中间值,center为最小值,high为最大值
//pre:high>low,两元素时也适用,可以传给Partition不出错
int center=(low+high)/2;
if (arr[high]<arr[low])
Swap(arr[high],arr[low]);
if (arr[high]<arr[center])
Swap(arr[high],arr[center]);
if (arr[low]<arr[center])
Swap(arr[low],arr[center]);
return arr[low];
}
void Sort::Swap(ElemType &e1,ElemType &e2)
{
ElemType tmp=e1;
e1=e2;
e2=tmp;
}
main.cc
/*-----------------------------------------------
Created By EverSteins
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/
#include "stdafx.h"
#include <iostream>
#include "utility.h"
#include "quick_sort.h"
using namespace std;
typedef int ElemType;
void PrintArray(const ElemType *arr,int n);
int _tmain(int argc, _TCHAR* argv[])
{
int arr[]={8,7,6,5,4,3,2,1,9};
int n=sizeof(arr)/sizeof(arr[0]);
PrintArray(arr,n);
Sort::QuickSort(arr,n);
PrintArray(arr,n);
cin.get();
return 0;
}
void PrintArray(const ElemType *arr,int n)
{
for (int i=0;i<n;++i)
cout<<arr[i]<<' ';
cout<<endl;
}