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

  • 相关阅读:
    在禅道中实现WORD等OFFICE文档转换为PDF进行在线浏览
    慎用 supportedRuntime
    定时开关机方案
    谨慎使用Sql server data tool 架构比对排除
    生成数据字典
    Cordova开发速记
    SQLSERVER 2012 收缩日志
    QService 服务容器
    使用用户自定义类型 CLR UDT
    使用DOTNETZIP过滤并压缩相对目录
  • 原文地址:https://www.cnblogs.com/warnet/p/3825803.html
Copyright © 2011-2022 走看看