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

全部博文(633)

文章存档

2011年(10)

2010年(500)

2009年(47)

2008年(76)

我的朋友

分类:

2008-05-24 23:52:17

Suppose you have a group o N numbers and would like to determine the kth largest.This is known as the selection problem.
 
One way to solve this problem would be to read the N numbers into an arriy, sort the array in decreasing order by some simple algorithm such as bubblesort, and then return the element in position k.

下面是我的代码:

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

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

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

void my_sort(int arriy[], int n) /*from large to small*/
{
    int i, j, tmp;

    for (i = 0; i < n; i++)
        for (j = 0; j < n - i - 1; j++)
        {
            if (arriy[j] < arriy[j + 1])
            {
                tmp = arriy[j];
                arriy[j] = arriy[j + 1];
                arriy[j + 1] = tmp;
            }        
        }
    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 <= 0 || 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);
    }

    get_input(p_arriy, n);
    my_sort(p_arriy, n);
    show_arriy(p_arriy, n);
    printf("the %dth number is %d\n", k, p_arriy[k - 1]);
    
    return 1;
}

阅读(896) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~