二次元配列の二分探索、書いてみました。
C
1#include <stdio.h>
2#include <stdlib.h>
3
4#define N 12
5#define M 16
6
7int mat[N][M] = {
8 1, 5, 8, 10, 14, 16, 20, 23, 24, 26, 28, 31, 35, 38, 42, 46,
9 8, 9, 12, 13, 15, 20, 21, 27, 29, 32, 35, 38, 42, 46, 50, 52,
10 11, 14, 17, 19, 23, 25, 26, 31, 34, 36, 38, 40, 46, 47, 52, 55,
11 16, 20, 23, 25, 28, 32, 33, 34, 36, 39, 42, 43, 48, 50, 54, 56,
12 24, 25, 27, 30, 32, 34, 36, 37, 41, 44, 46, 49, 53, 56, 57, 61,
13 31, 35, 36, 37, 40, 41, 42, 46, 50, 53, 57, 58, 59, 60, 61, 65,
14 36, 39, 42, 45, 49, 53, 56, 59, 62, 66, 68, 70, 73, 75, 76, 77,
15 41, 43, 44, 48, 51, 55, 58, 60, 66, 67, 70, 74, 76, 78, 82, 84,
16 45, 47, 51, 55, 56, 58, 60, 63, 68, 71, 75, 79, 80, 81, 86, 87,
17 51, 55, 59, 62, 63, 64, 68, 69, 71, 72, 79, 82, 84, 87, 91, 93,
18 55, 59, 60, 63, 64, 66, 71, 73, 74, 77, 80, 83, 87, 91, 92, 97,
19 59, 63, 65, 69, 70, 71, 75, 77, 78, 82, 86, 89, 91, 94, 98, 99,
20};
21
22void search(int v, int a, int b, int c, int d)
23{
24 if (a > b || c > d) return;
25 int i = (a + b) / 2, j = (c + d) / 2;
26 if (mat[i][j] > v) {
27 search(v, a, i-1, c, d);
28 search(v, i, b, c, j-1);
29 }
30 else if (mat[i][j] < v) {
31 search(v, a, i, j+1, d);
32 search(v, i+1, b, c, d);
33 }
34 else printf(" (%d,%d)", i, j);
35}
36
37int main(void)
38{
39 for (int i = 0; i < N; i++) {
40 for (int j = 0; j < M; j++)
41 printf("%3d", mat[i][j]);
42 putchar('\n');
43 }
44 int v;
45 while (printf(">> "), scanf("%d", &v) == 1) {
46 search(v, 0, N-1, 0, M-1);
47 putchar('\n');
48 }
49}
実行例
1 5 8 10 14 16 20 23 24 26 28 31 35 38 42 46
8 9 12 13 15 20 21 27 29 32 35 38 42 46 50 52
11 14 17 19 23 25 26 31 34 36 38 40 46 47 52 55
16 20 23 25 28 32 33 34 36 39 42 43 48 50 54 56
24 25 27 30 32 34 36 37 41 44 46 49 53 56 57 61
31 35 36 37 40 41 42 46 50 53 57 58 59 60 61 65
36 39 42 45 49 53 56 59 62 66 68 70 73 75 76 77
41 43 44 48 51 55 58 60 66 67 70 74 76 78 82 84
45 47 51 55 56 58 60 63 68 71 75 79 80 81 86 87
51 55 59 62 63 64 68 69 71 72 79 82 84 87 91 93
55 59 60 63 64 66 71 73 74 77 80 83 87 91 92 97
59 63 65 69 70 71 75 77 78 82 86 89 91 94 98 99
>> 1
(0,0)
>> 99
(11,15)
>> 50
(1,14) (3,13) (5,8)
>> 18
>> 100
>> 37
(4,7) (5,3)
>> .