Fast sorting algorithms repeat element (three-slicing)

Author:GuangshengZhou
QQ:825672792

Problem Description

Recently used in a project in a quick sort, but once the duplicate data appears in the array, quick sort on a great chance to get into the dead through the bad, because the sorting process is repeated for a number of groups of elements equal swap. Now the algorithm minor modifications, additions equal determination condition, i.e. a third of the cut.

Encoding function

Directly following the code.

//交换函数
void swap(int & nFirst, int & nSecond){
	nFirst = nFirst + nSecond;
	nSecond = nFirst - nSecond ;
	nFirst = nFirst  - nSecond ;
}

// 快速排序
void quicksort(int nArray[], int nLeft, int nRight){
	if(nLeft >= nRight){
		return;
	}
	//临时数据
	int left = nLeft, lcur = nLeft, lcount = 0;
	int right = nRight, rcur = nRight, rcount = 0;
	
	int nValue = nArray[left];

	while(left < right){
		while(left < right &&  nValue <= nArray[right])
		{
			if(nValue == nArray[right]){
				swap(nArray[rcur], nArray[right]);
				rcur--;
				rcount++;
			}
			right--;
		}
		if(left < right){
			nArray[left++] = nArray[right];
		}
		while(left < right && nArray[right] >= nValue){
		 	if(nArray[left] == nValue){
		 		swap(nArray[lcur], nArray[left]);
		 		lcur++;
		 		lcount++;
		 	}
		 	left++;
		} 
		if(left < right){
			nArray[right--] = nArray[left];
		}
	}
	
	nArray[left] = nValue;
	assert(left == right);
	
	//交换右边相等区域
	int index = right + 1;
	while(rcount > 0 && index <= rcur && (nRight - (index-(right + 1))>rcur)){
		swap(nArray[index,], nArray[nRight - (index - (right + 1)]);
		index++;
	}
	//交换左边相等区域
	index = left - 1;
	while(lcount > 0 && indx >= lcur && (nLeft + (left - 1 - index) < lcur)){
		swap(nArray[index,], nArray[nRight - (nLeft + (left - 1 - index)]);
		index--;
	}
}

Results show

int main(){
	int array[10] = {30, 20, 30, 50, 60, 30, 30, 40, 40, 35};
	quicksort(array, 0, 10);
	for(int i = 0; i < 10; i++){
  		printf("%d \n", array[i]);
  	}
}

Remark

Since the company network with the code pure hand to play, the program may not be the best solution, only for exchange of learning.

Released two original articles · won praise 2 · Views 422

Guess you like

Origin blog.csdn.net/u010158920/article/details/105090779