C#顺序查找与二分查找
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ConsoleApplication1
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 int[] arr = new int[] { 1, 3, 5, 6, 7, 8, 9 };
13 int key = 8;
14 int retValue;
15 retValue = binarySearching(arr, 0, arr.Length - 1, key);
16 if (retValue == -1)
17 System.Console.WriteLine("{0} 在查找表中不存在", key);
18 else
19 System.Console.WriteLine("{0} 在查找表中的位置为 {1}", key, retValue);
20 }
21 /*順序查找*/
22 static int sequenceSearching(int[] arr, int len, int key)
23 {
24 int i;
25
26 for (i = 0; i < len && arr[i] != key; i++) ;
27 if (i < len)
28 {// 找到了,因为arr[i]==key
29 return i;
30 }
31 else
32 {//没找到
33 return -1;
34 }
35 //return (i<len)?(i):(-1);
36 }
37 /** 二分查找算法
38 * 从开始位置 low 到结束位置 high 的查找表 arr 中查找值为 key的记录
39 * 若存在,返回该元素所在的下标;
40 * 否则,返回 -1
41 */
42 static int binarySearching(int[] arr, int low, int high, int key)
43 {
44 int mid;
45
46 while (low <= high)
47 {
48 mid = (low + high) / 2;
49 if (arr[mid] == key) //找到
50 return mid;
51 else if (arr[mid] > key) //在左边部分继续查找
52 high = mid - 1;
53 else //在右边部分继续查找
54 low = mid + 1;
55 }
56 return -1;
57 }
58 }
59
60
61 }