Q:在元素集合中查找第k小元素,即查找到的元素在排序后的集合内排在第K的位置。
Sol:利用快速排序中的切分函数,可以递归的查找第K个元素。
具体步骤:
1,在元素集合中选择一个枢纽元
2,确定枢纽元在元素集合中的位置(利用快速排序中的切分函数)
3,确定枢纽元在元素集中的位置与K的关系继续在切分后的子集合中查找第K元素,具体关系代码说得较仔细
一般版本的切分函数,原理代码说的很清楚:
int partition(int arr[],int left,int right,int pivotIndex)
{
int i,j,pivot,temp;
i = left;
j = right;
pivot = arr[pivotIndex];
/*swap arr[pivotIndex] and arr[right]*/
temp = arr[pivotIndex];
arr[pivotIndex] = arr[right];
arr[right] = temp;
/*init j*/
j = left;
/*shift all elements smaller than pivot to the left end*/
for(i=left;i<right;i++)
{
if (arr[i]<pivot)
{
/*swap arr[i] and arr[store]*/
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;