首页 > 代码库 > 查找序列中第K小的数与快速排序

查找序列中第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小的数与快速排序