1 int[] a = new int[20] { 2, 3, 6, 7, 12, 18, 19, 21, 25, 28, 30, 33, 37, 39, 42, 45, 47, 49, 50, 51 }; 2 int x = 18, i; 3 string j, k; 4 var d = find(a, x, 0, 19); 5 if (d == -1) 6 { 7 k = String.Format("未找到{0}", x); 8 } 9 else10 {11 for (i = 0; i < 20; i++)12 {13 if ((i = d) > 0)14 {15 j = String.Format("{0}是第{1}个数\n", x, i + 1);16 break;17 }18 }19 }
find方法如下:
1 int find(int[] a, int x, int n, int m)2 {3 int i;4 if (n > m) return -1;5 i = (n + m) / 2;6 if (a[i] == x) return i;7 if (a[i] > x) return find(a, x, n, i - 1);8 return find(a, x, i + 1, m);9 }
可以输出j
显示查找结果
good luck ----------