码迷,mamicode.com
首页 > 其他好文 > 详细

查找一个数组中最小的前n项

时间:2014-07-06 13:12:01      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:for   io   amp   size   har   ui   


/*****************************************************************
* find the biggest x number in a sequence
* the basic method is the same as the QuickSort
*
* 1. move the smaller one before the pivot
* 2. move the bigger one after the pivot
* 3. determin whether the X matches the pivot‘s index
* 3.1 if y return the index
* 3.2 if n recursively call the func with proper param
*
*****************************************************************/
#define cnt 10
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>


int findBiggestX(int* pa, int low, int high, int key);

int main(void)
{

int arr[cnt];
int i=0;
int key = 4;
printf("arr is :\n");
srand((unsigned)time(NULL));//use current time as seed
for(i=0;i<cnt;i++)
{
arr[i]=rand()%100;
printf("%d\t",arr[i]);
}
printf("\n\n");

findBiggestX(arr,0,sizeof(arr)/sizeof(int)-1,key);
for(i=0;i<cnt;i++)
{
printf("%d\t",arr[i]);
}
printf("\n");
for(i=0;i<key;i++)
{
printf("%d\t",arr[i]);
}
printf("\n");
getchar();
return 0;
}

int findBiggestX(int* pa, int low, int high, int key)
{
int pivot = pa[0];
int low_temp = low;
int high_temp = high;
while(low<high)
{
while(pa[high]>=pivot && low<high)
{
high--;
}
pa[low]=pa[high];
while(pa[low]<=pivot && low<high)
{
low++;
}
pa[high]=pa[low];
}
pa[low]=pivot;
if(key-1 == low)
{
return low;
}
else if(key-1 < low)
{
return findBiggestX(pa,low_temp,low,key);
}
else
{
return findBiggestX(pa,low+1,high_temp,key);
}
}

 

查找一个数组中最小的前n项,布布扣,bubuko.com

查找一个数组中最小的前n项

标签:for   io   amp   size   har   ui   

原文地址:http://www.cnblogs.com/warnet/p/3825803.html

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