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;
}
|
阅读(902) | 评论(0) | 转发(0) |