# 重复元素的快速排序算法(三向切分)

Author:GuangshengZhou
QQ:825672792

# 函数编码

//交换函数
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--;
}
}


# 结果验证

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]);
}
}


# 备注

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客