C++_快速排序(纯C版本)

//比较大小

static int compare_int(const void *int1,const void *int2)
{
	if(*(const int*)int1>*(const int*)int2)
	{
		return 1;
	}
	else if(*(const int*)int1<*(const int*)int2)
	{
		return -1;
	}
	else
	{
		return 0;
	}
}

//随机生成三个数,找出中间数的直接插入排序

int issort(void *data, int size,int esize,int (*compare)(const void *key1,const void *key2))
{
	char *a = (char*)data;

	void *key=NULL;
	
	int i=0,j=0;

	if((key=(char *)malloc(esize))==NULL)
	{
		return -1;
	}
	else
	{
		memset(key, 0, esize);
		for(j=1;j<size;j++)
		{
			memcpy(key, &a[j*esize],esize);
			i=j-1;

			while(i>=0&&compare(&a[i*esize],key)>0){
				memcpy(&a[(i+1)*esize],&a[i*esize],esize);
				i--;
				cout<<i<<endl;
			}

			memcpy(&a[(i+1)*esize],key,esize);
			
		}
		free(key);
		return 0;
	}

}

//与当前pval相比,小的放左边,大的放右边,pval即r[1]

static int partition(void *data, int esize, int i, int k, int (*compare)(const void *key1,const void *key2))
{
	//cout<<"enter partition"<<endl;
	char *a=(char*)data;

	void *pval=NULL, *temp=NULL;

	int r[3]={0,0,0};

	//allocate storage for the partition value and swap
	if((pval = malloc(esize))==NULL)
	{
		return -1;
	}
	if((temp = malloc(esize))==NULL)
	{
		free(pval);
		return -1;
	}


	//Use the median-of-tree method to find the partition value
	r[0] = (rand() % (k-i+1))+i;
	r[1] = (rand() % (k-i+1))+i;
	r[2] = (rand() % (k-i+1))+i;
	
	issort(r, 3,  sizeof(int), compare_int);

   	memcpy(pval, &a[r[1]*esize],esize);
	

	//cout<<"*pval= "<<(pval)<<endl;
   	//create two partitions around the partition value

	i--;
	k++;
   //	cout<<"this is i: "<<i<<endl;
   //	cout<<"this is k: "<<k<<endl;
   	
   	while(1)
   	{

   		do{
   		//	cout<<"doing k"<<endl;
   			k--;
   		}while(compare(&a[k*esize],pval)>0);

   		do{
   		//	cout<<"doing i"<<endl;
   			i++;
   		}while(compare(&a[i*esize],pval)<0);

   		if(i >= k)
   		{
   		//	cout<<"doing break"<<endl;
   			break;
   		}
   		else
   		{
   		//	cout<<"swaping......................."<<endl;
   			memcpy(temp, &a[i*esize], esize);
   			memcpy(&a[i*esize], &a[k*esize], esize);
   			memcpy(&a[k*esize], temp, esize);
   		}
   	}

   	free(pval);
   	free(temp);
  // 	cout<<"left partition"<<endl;
   	
	return k;
}
//排序调用

int qksort(void *data, int size, int esize, int i, int k, int (*compare)(const void *key1,const void *key2))
{
	int j;
	while(i<k)
	{
		if((j=partition(data,esize,i,k,compare))<0)
		{
			//cout<<"return partition"<<endl;
			return -1;
		}
		
		if(qksort(data,size,esize,i,j,compare)<0)
		{
			//cout<<"return qksort"<<endl;
			return -1;
		}
		
		else
		{
			i=j+1;
			//cout<<"i value: "<<i<<endl;
			//cout<<"j value: "<<j<<endl;
		}
	}

	return 0;
}



原文地址:https://www.cnblogs.com/MarchThree/p/3720481.html