算法导论中的快速排序算法:
// QuickSort1.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 Exchange(int &number1, int &number2);//交换
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:"<<endl;
Print(array,length);
QuickSort(array,0,length-1);
cout<<"After QuickSort:"<<endl;
Print(array,length);
getchar();
return 0;
}
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 i,j;
int flag=array[high];
i=low-1;
for (j=low;j<high;j++)
{
if (array[j]<=flag)
{
i++;
Exchange(array[i],array[j]);
}
}
Exchange(array[i+1],array[high]);
return i+1;
}
void Exchange(int &number1, int &number2)
{
int temp;
temp=number1;
number1=number2;
number2=temp;
}
void Print(int array[], int length)
{
int i;
for (i=0;i<length;i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
}