闲来无事,实现了一下随机选择算法,从一堆数中找出第i大的数,主要的几个函数如下:
[test]
[result]
./rand_select 6 3
2
1
5
6
9
10
array[2, 1, 5, 6, 9, 10, ]
the 3th large num is [5]
<=A[r] | r | >=A[r] |
- /* 查找第i大的数 */
- int rand_select(int *array, int beg_index, int end_index, int select)
- {
- if (beg_index == end_index)
- return array[beg_index];
- int pos = rand_partition(array, beg_index, end_index);
- int rank = pos - beg_index + 1;
- if (rank == select)
- return array[pos];
- else if (rank < select)
- return rand_select(array, pos + 1, end_index, select - rank);
- else
- return rand_select(array, beg_index, pos - 1, select);
- }
- /* 随机分区 */
- int rand_partition(int *array, int beg_index, int end_index)
- {
- srand((int)time(NULL));
- int pivot = (rand() % (end_index - beg_index + 1)) + beg_index;
- if (pivot != beg_index) {
- array_switch(array, pivot, beg_index);
- }
- int i = beg_index;
- int j = i + 1;
- for (; j <= end_index; j++) {
- if (array[j] < array[beg_index]) {
- array_switch(array, j, ++i);
- }
- }
- array_switch(array, i, beg_index);
- return i;
- }
- /* 交换数 */
- void array_switch(int *array, int index1, int index2)
- {
- int tmp = array[index1];
- array[index1]= array[index2];
- array[index2] = tmp;
- }
[test]
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- int rand_select(int *array, int beg_index, int end_index, int select);
- int rand_partition(int *array, int beg_index, int end_index);
- void array_switch(int *array, int index1, int index2);
- int main(int argc, char *argv[])
- {
- if (argc < 2) {
- printf("usage: %s <array num> <kth large num>/n", argv[0]);
- return -1;
- }
- int num = atoi(argv[1]);
- int select = atoi(argv[2]);
- if (select > num) {
- printf("not enough num, array num[%d], kth large num[%d]/n",
- num, select);
- return -1;
- }
- int *array = (int *)malloc(sizeof(int) * num);
- if (array == NULL) {
- printf("malloc failed/n");
- return -1;
- }
- array[0] = 0;
- int i = 0;
- for (; i < num; i++) {
- scanf("%d", &array[i]);
- }
- printf("array[");
- for (i = 0; i < num; i++) {
- printf("%d, ", array[i]);
- }
- printf("]/n");
- int pic = rand_select(array, 0, num - 1, select);
- printf("the %dth large num is [%d]/n", select, pic);
- return 0;
- }
[result]
./rand_select 6 3
2
1
5
6
9
10
array[2, 1, 5, 6, 9, 10, ]
the 3th large num is [5]