随机选择第i小元素

来源:互联网 发布:景观设计需要哪些软件 编辑:程序博客网 时间:2024/05/22 07:43

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.总结
分而治之思想。