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

  • 相关阅读:
    Markdown 语法说明 (简体中文版)
    Markdown Reference
    BZOJ 2229 最小割
    BZOJ 3569 DZY Loves Chinese II
    BZOJ 3563 DZY Loves Chinese
    BZOJ 2956 模积和
    BZOJ 2957 楼房重建
    查漏补缺:面向对象设计原则
    添砖加瓦:设计模式(简单工厂模式)
    添砖加瓦:设计模式(总述)
  • 原文地址:https://www.cnblogs.com/warnet/p/3825803.html
Copyright © 2011-2022 走看看