您的位置:首页 > 其它

随机选择第i小元素

2017-12-11 15:47 375 查看
1.思路

采用快速排序中的Partition(int *nArr, int nLeft, int nRight)函数,将数组nArr按照与随机选取Key值的大小关系进行排序,检查比key值所处位置nKey(nKey = nTmpPos - nLeft + 1)和i的关系,如果nKey=i,则返回nArr[nKey];如果nKey > i,则调用Select(nArr, nLeft, nTmpPos- 1, i),如果nKey < i,则调用Select(nArr, nTmpPos+ 1, nRight, i - nKey)

2.主要代码

int Partition(int *pnArr, int nLeft, int nRight)  //一次循环版快排
{
int nKey = nRight;
int i = nLeft - 1;
for (int j = nLeft; j < nRight; j++)
{
if (pnArr[j] <= pnArr[nKey])
{
i++;
Swap(&pnArr[i], &pnArr[j]);
}
}

Swap(&pnArr[i+1], &pnArr[nKey]);
return i+1;
}

int RandomPartiton(int *pnArr, int nLeft, int nRight) //随机选择key值
{
srand(time(NULL));
int i = rand()%(nRight - nLeft + 1) + nLeft;
Swap(&pnArr[i], &pnArr[nRight]);

return Partition(pnArr, nLeft, nRight);
}
//i  第i小元素
int RandomSelect(int *pnArr, int nLeft, int nRight, int i) //主要函数
{
if (nLeft == nRight)
{
return pnArr[nLeft];
}
//寻找一个nTmpPos下标,nTmpPos左边的值都小于它,右边的值都大于它
int nTmpPos = RandomPartiton(pnArr, nLeft, nRight);

int nLCount = nTmpPos - nLeft + 1;
if (nLCount == i)
{
return pnArr[nTmpPos];
}
else if (i  < nLCount)
{
return RandomSelect(pnArr, nLeft, nTmpPos - 1, i);
}
else
{
return RandomSelect(pnArr, nTmpPos + 1, nRight, i - nLCount);
}
}


3.总结

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