查找序列中第K小的数与快速排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了查找序列中第K小的数与快速排序相关的知识,希望对你有一定的参考价值。
#include <algorithm>
#include <iostream>
int Partition(int X[], int left, int right)
{
int pivot = X[left];
int L = left;
int R = right;
while(L < R)
{
while(X[L] <= pivot && L < right)
{
++L;
}
while(X[R] > pivot && R > left)
{
--R;
}
if (L < R)
{
std::swap(X[L], X[R]);
}
}
std::swap(X[left], X[R]);
return R;
}
void Procedure(int X[], int left, int right)
{
if (left < right)
{
int middle = Partition(X, left, right);
Procedure(X, left, middle-1);
Procedure(X, middle+1, right);
}
}
void QSort(int X[], int count)
{
Procedure(X, 0, count-1);
}
int ProcedureSelect(int X[], int left, int right, int k)
{
if (left == right)
{
return X[left];
}
else
{
int middle = Partition(X, left, right);
if (middle - left + 1 >= k)
{
return ProcedureSelect(X, left, middle, k);
}
else
{
return ProcedureSelect(X, middle+1, right, k - (middle - left +1));
}
}
}
int Select(int X[], int count, int k)
{
if (k < 1 || k > count)
{
std::cout << " ERROR" << std::endl;
return -1;
}
else
{
return ProcedureSelect(X, 0, count-1, k);
}
}
以上是关于查找序列中第K小的数与快速排序的主要内容,如果未能解决你的问题,请参考以下文章