算法導論 改進快排(2)----針對相同元素值 7.2

問題:序列中有較多相同元素值時,隨機化快排的性能下降

思路:PARTION將序列分爲三個部分A(p,q,t,r),A[p,...,q-1]中元素都小於A[q],A[q,...,t]中元素都相等,A[t+1,...,r]中元素都大於A[q]。QUICKSORT只對分區內互不相同的元素才做遞             歸。

代碼:

#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;

void Swap(int &a, int &b)//交換兩個數的函數
{
	int temp=b;
	b=a;
	a=temp;
}

int* New_Partition(int *A, int p, int r)  //新的分區函數    
{      
    int *index=new int[2];
	int k=rand()%(r-p+1)+p;//隨機化快排
	Swap(A[k],A[r]);
	int i=p-1;
	for(int j=p;j<r;j++) //把比主元小的元素都排到前面
	{
		if (A[j]<A[r])
		{
			++i;
			Swap(A[i],A[j]);
		}
	}
	index[0]=i+1;//記錄相等元素開始的下標
	for(int l=i+1;l<r;l++)//再把和主元相等的元素排到中間
	{
		if (A[l]==A[r])
		{
			++i;
			Swap(A[l],A[i]);
		}
	}
	index[1]=i+1;//記錄相等元素結束的下標
	Swap(A[i+1],A[r]);
	return index;
} 
     
void QuickSort(int  *A, int p, int r)      
{  
    
    if(p < r)      
    {      
        int *new_index= New_Partition(A, p, r); 
        QuickSort(A, p, new_index[0]-1); 
        QuickSort(A, new_index[1]+1, r);
		delete [] new_index;
    }      
} 

int main()
{
	int A[9]={2,1,3,5,8,4,1,4,4};
	for(int m=0;m<=8;m++)
			cout<<A[m]<<" ";
	cout<<endl;
	srand((unsigned)time(NULL));
	QuickSort(A,0,8);
	for(int n=0;n<=8;n++)
			cout<<A[n]<<" ";
	cout<<endl;
	return 0;
} 




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章