zoukankan      html  css  js  c++  java
  • 查找一个数组中最小的前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 : ");
    srand((unsigned)time(NULL));//use current time as seed
    for(i=0;i<cnt;i++)
    {
    arr[i]=rand()%100;
    printf("%d ",arr[i]);
    }
    printf(" ");

    findBiggestX(arr,0,sizeof(arr)/sizeof(int)-1,key);
    for(i=0;i<cnt;i++)
    {
    printf("%d ",arr[i]);
    }
    printf(" ");
    for(i=0;i<key;i++)
    {
    printf("%d ",arr[i]);
    }
    printf(" ");
    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);
    }
    }

  • 相关阅读:
    第13章 TCP/IP和网络编程
    实验二测试
    实验四 Web服务器1socket编程
    thread同步测试
    团队作业(五):冲刺总结——第四天
    111
    递归和数学归纳法
    Nodejs中cluster模块的多进程共享数据问题
    JavaScript写类方式(一)——工厂方式
    JavaScript中的shift()和pop()函数
  • 原文地址:https://www.cnblogs.com/warnet/p/3825803.html
Copyright © 2011-2022 走看看