/*
*快排的基本思想:
* 现在源数据中任意去一个值,作为标准值。把
* 数据中小于标准值的数据排在该标准值的左边,把
* 数据中大于等于标准值的数据排在该标准值的右边。
* 这样就分成了三部分。
* 左半边 标准值 右半边
*然后分别在左半边和右半边进行取标准值,划分左半
*边和右半边。
*
*可用到递归思想或栈的数据结构
*/
#include <iostream>
#include <iomanip>
using namespace std;
#define Size 20
typedef int DataType;
void QuickSort(DataType digit[], int low, int high);
void PaintQuickSort(DataType digit[], int lengthOfDigit);
int main(void)
{
DataType digit[Size] ={
12, 45, 56, 56, 98,
23, 44, 22, 49, 78,
34, 26, 65, 84, 73,
28, 45, 84, 74, 88};
PaintQuickSort(digit, Size);
QuickSort(digit, 0, Size-1);
PaintQuickSort(digit, Size);
return 0;
}
//快速排序
void QuickSort(DataType digit[], int low, int high)
{
int i = low;
int j = high;
DataType temp = digit[low]; // 选取标准值
while(i < j)//结束条件是 high <= low
{
while(i < j && temp < digit[j]) j--; // 在数组的右边扫描
if(i < j)
{
digit[i] = digit[j];
i++;
}
while(i < j && temp > digit[i]) i++; // 在数组的左边扫描
if(i < j)
{
digit[j] = digit[i];
j--;
}
}
digit[i] = temp;
if( low < i) QuickSort(digit,low, i-1); //递归
if( i < high) QuickSort(digit, i+1, high);//递归
cout<<"After QuickSort..."<<endl;//帮助你理解递归
}
///输出
void PaintQuickSort(DataType digit[], int lengthOfDigit)
{
for(int i = 0; i < lengthOfDigit; i++)
{
cout<<digit[i]<<setw(3);
}
cout<<endl;
}
快速排序
最新推荐文章于 2023-12-01 23:14:38 发布