码迷,mamicode.com
首页 > 编程语言 > 详细

查找序列中第K小的数与快速排序

时间:2016-12-22 11:38:19      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:err   排序   swap   algo   sort   end   partition   sel   ++   

#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小的数与快速排序

标签:err   排序   swap   algo   sort   end   partition   sel   ++   

原文地址:http://www.cnblogs.com/fullnamefull/p/6210018.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!