第二种快速排序,与快排(一)唯一不同的地方是Partition()函数,两者技巧不同,本质都一样都是实现一次快排。
// QuickSort2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
#include <ctime>
void QuickSort(int array[], int low, int high);
int Partition(int array[], int low, int high);
void Print(int array[], int length);
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned)time(NULL));//以时间为种子随机产生随机数
int length=rand()%20;
int *array=new int[length];//动态数组
for(int i=0;i<length;i++)
{
array[i]=rand()%100;
}
cout<<"Before quicksort,the array:"<<endl;
Print(array,length);
QuickSort(array,0,length-1);
cout<<"Before quicksort,the array:"<<endl;
Print(array,length);
getchar();
return 0;
}
void Print(int array[], int length)
{
for (int i=0;i<length;i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
}
void QuickSort(int array[], int low, int high)
{
int mid;
if (low<high)
{
mid=Partition(array,low,high);
QuickSort(array,low,mid-1);
QuickSort(array,mid+1,high);
}
}
int Partition(int array[], int low, int high)//与快速排序(一)唯一不同的地方
{
int flag=array[low];
while(low<high)
{
while(low<high&&array[high]>=flag)
{
high--;
}
array[low]=array[high];
while(low<high&&array[low]<=flag)
{
low++;
}
array[high]=array[low];
}
array[low]=flag;
return low;
}