#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <stack>
using namespace std;
static ncount = 0;
//非遞歸普通快速
void exchange(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void prints(int a[], int len)
{
for (int i = 0; i < len; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
}
int Partition(int a[], int low, int high)
{
int privot = a[low];
printf("a[low] = %d \n", a[low]);
while (low < high)
{
while ( low < high && a[high] >= privot)
{
high--;
ncount++;
}
if (low < high)
{
exchange(a[low++], a[high]);
prints(a, 8);
}
while (low < high && a[low] <= privot)
{
low++;
ncount++;
}
if (low < high)
{
exchange(a[low], a[high--]);
prints(a, 8);
}
ncount++;
}
// a[low] = privot;
printf("a[low] = %d \n", a[low]);
return low;
}
void sort(int a[], int low, int high)
{
int pivolt;
if (low < high)
{
pivolt = Partition(a, low, high);
sort(a, low, pivolt-1);
sort(a, pivolt + 1, high);
}
}
int main(void)
{
int a[] = {13, 27, 55, 63, 7, 8, 15, 16, 12, 1, 1 ,1 ,1 ,1 ,1};
sort(a, 0, sizeof(a)/sizeof(int) - 1);
for (int i = 0; i < sizeof(a)/sizeof(int); ++i )
{
printf("%d ", a[i]);
}
printf("\n");
printf("%d\n", ncount);
return 1;
}
//平衡快速,適用於催向順序的排列
void QuickSort(int *pData,int left,int right)
{
int i(left),j(right),middle(0),iTemp(0);
middle=pData[(left+right)/2];//求中間值
middle=pData[(rand()%(right-left+1))+left]; //生成大於等於left小於等於right的隨機數
do{
while((pData[i]<middle)&&(i<right))//從左掃描大於中值的數
{
i++;
ncount++;
}
while((pData[j]>middle) && (j>left))//從右掃描小於中值的數
{
j--; //找到了一對值,交換
ncount++;
}
if(i<=j){
iTemp=pData[j];
pData[j]=pData[i];
pData[i]=iTemp;
i++;
j--;
}
ncount++;
}while(i<=j);//如果兩邊掃描的下標交錯,就停止(完成一次) //當左邊部分有值(left<j),遞歸左半邊
if(left<j){
QuickSort(pData,left,j);
} //當右邊部分有值(right>i),遞歸右半邊
if(right>i){
QuickSort(pData,i,right);
}
}
//非遞歸版快速排序
struct Num
{
int low,high;
Num(int low = 0, int high = 0)
{
this->low = low;
this->high = high;
}
};
void sort(int val[],int ,int );
int main()
{
int arg[] = {13, 27, 55, 63, 7, 8, 15, 16, 12, 1, 1 ,1 ,1 ,1 ,1};
sort(arg,0,sizeof(arg)/sizeof(int)-1);
for(int i = 0; i < sizeof(arg)/sizeof(int); i++)
{
cout<<arg[i]<<" ";
}
system("pause");
return 0;
}
void sort(int arr[], int begin, int end)
{
std::stack<Num> myStack;
myStack.push(Num(begin, end));
while(!myStack.empty())
{
int i = myStack.top().low;
int j = myStack.top().high;
int b = i;
int e = j;
myStack.pop();
if(i >= j)
continue;
int key = arr[i];
while(i < j)
{
while(i < j && arr[j] >= key)
j--;
if(i < j)
arr[i++] = arr[j];
while(i < j && arr[i] <= key)
i++;
if(i < j)
arr[j--] = arr[i];
}
arr[i] = key;
printf("%d\n", i);
myStack.push(Num(b, i - 1));
myStack.push(Num(i + 1, e));
}
}