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


/*****************************************************************
* 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);
}
}

 

posted @ 2014-07-05 15:14  warnet  阅读(322)  评论(0编辑  收藏  举报