# 求无序数组第K大小的数值

397人阅读 评论(0)

#include "stdafx.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

void swap(int & a, int & b);
int find_position(int* a,int k, int low,int high);
int find_orderk(int* a, int k, int low,int high);

void swap(int & a, int & b)
{
int tmp = a;
a = b;
b = tmp;
}

int find_position(int* a,int k, int low,int high)
{
if (low >= high)
{
return low;
}

int m = rand() % (high - low) + low;
int tmp =  a[m];
int p = m;

int lowpos = low;
bool bfindlow = false;
for (int i = low; i < m; i++)
{
if (a[i] >= tmp && bfindlow)
{
swap(a[lowpos++], a[i]);
}
else if(a[i] < tmp && !bfindlow)
{
lowpos = i;
bfindlow = true;
}
}

if (bfindlow)
{
swap(a[lowpos], a[m]);
p = lowpos;
}

int highpos = p;
lowpos = p+1;
bool bfindhigh = false;
for (int i = m+1; i <= high; i++)
{
if (a[i] >= tmp)
{
highpos = i;
if (!bfindhigh)
{
bfindhigh = true;
}

if(bfindlow)
{
highpos = lowpos;
swap(a[lowpos++], a[i]);
}
}
else
{
if(!bfindlow)
{
bfindlow = true;
lowpos = i;
}
}
}

if(bfindhigh)
{
swap(a[p], a[highpos]);
p = highpos;
}

return p;
}

int find_orderk(int* a, int k, int low,int high)
{
int p = find_position(a, k-1+low, low, high);

if(p-low < k-1)
{
p = find_orderk(a, (k-1)-(p-low), p+1, high);
}
else if (p-low > k-1)
{
p = find_orderk(a, k, low, p-1);
}

return p;
}

int main ()
{
srand((unsigned) time(NULL));
int k = 1;
while (k <= 10)
{
int a[10]={9,11,6,2,8,12,7,3,20,1};
int p = find_orderk(a, k, 0, 9);

printf("\n NO. %d  VALUE : %d\n", k, a[p]);
k++;
}
return 0;
}



0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：28124次
• 积分：575
• 等级：
• 排名：千里之外
• 原创：29篇
• 转载：5篇
• 译文：0篇
• 评论：3条
文章分类
最新评论