Chinaunix首页 | 论坛 | 博客
  • 博客访问: 999830
  • 博文数量: 633
  • 博客积分: 30780
  • 博客等级: 大将
  • 技术积分: 7532
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-12 21:07
文章分类

全部博文(633)

文章存档

2011年(10)

2010年(500)

2009年(47)

2008年(76)

我的朋友

分类:

2008-05-25 00:45:59

Suppose you have a group o N numbers and would like to determine the kth largest.This is known as the selection problem.

#include <stdio.h>
#include <stdlib.h>

void get_input(int arriy[], int k)
{
    int i = 0;
    for (; i < k; i++)
    {
        scanf("%d", arriy + i);
    }

    return;
}

void my_sort(int arriy[], int k)
{
    int i, j, tmp;
    for (i = 0; i < k; i++)
        for (j = 0; j < k - i -1; j++)
        {
            if (arriy[j] < arriy[j+1])
            {
                tmp = arriy[j];
                arriy[j] = arriy[j+1];
                arriy[j+1] = tmp;
            }
        }

    return;
}

void show_arriy(int arriy[], int k);
void my_replace(int arriy[], int k, int value)
{
    int position, i;
    position = 0;
    for (i = k - 1; i >= 0; i--)
    {
        if (arriy[i] < value)
            continue;
        else
        {
            position = i - 1;
            break;
        }
    }
    for (i = k - 1; i > position; i--)
    {
        arriy[i] = arriy[i - 1];
    }
    arriy[position] = value;
    return;
}


int read_and_result(int arriy[], int k, int r)
{
    int i, tmp;
    for (i = 0; i < r; i++)
    {
        scanf("%d", &tmp);
        if (tmp > arriy[k-1])
            my_replace(arriy, k, tmp);
        else
            continue;
    }
    
    return arriy[k-1];    
}

void show_arriy(int arriy[], int k)
{
    int i = 0;
    for (; i < k; i++)
        printf("%d ", *(arriy + i));
    printf("\n");

    return;
}

int main (int argc, char* argv[])
{
    if (argc != 3)
    {
        fprintf(stderr, "Usage: ./a.out n k\n");
        exit(1);
    }

    int n = atoi(argv[1]);
    int k = atoi(argv[2]);
    if (n < 1 || k < 1)
    {
        fprintf(stderr, "Usage: ./a.out n k\n");
        exit(1);
    }

    int *p_arriy = (int *)malloc(sizeof(int) * n);
    if (NULL == p_arriy)
    {
        fprintf(stderr, "stevens: malloc error!\n");
        exit(1);
    }
    /*remain n - k number to read from user*/
    get_input(p_arriy, k);
    my_sort(p_arriy, k);
    printf("the %dth number is %d\n", k, read_and_result(p_arriy, k, n-k));    
    return 1;

}

阅读(1175) | 评论(0) | 转发(0) |
0

上一篇:P1 Select Problem

下一篇:P5 Printing Out Numbers

给主人留下些什么吧!~~