您的位置:首页 > 其它

快速排序记录

2012-09-16 17:29 232 查看
#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));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: