using System;
namespace 查找算法
{
class Class1
{
static void Main(string[] args)
{
int[] arr = new int[]{1,3,5,6,7,8,9};
int key=80;
int retValue;
retValue = binarySearching(arr, 0, arr.Length-1, key);
if(retValue==-1)
System.Console.WriteLine("{0} 在查找表中不存在", key);
else
System.Console.WriteLine("{0} 在查找表中的位置为 {1}", key, retValue);
}
/** 顺序查找算法
* 从长度为 len 的查找表 arr 中查找值为 key的记录
* 若存在,返回该元素所在的下标;
* 否则,返回 -1
*/
static int sequenceSearching(int[] arr, int len, int key)
{
int i;
for(i=0; i<len && arr[i]!=key; i++);
if(i<len)
{// 找到了,因为arr[i]==key
return i;
}
else
{//没找到
return -1;
}
//return (i<len)?(i):(-1);
}
/** 二分查找算法
* 从开始位置 low 到结束位置 high 的查找表 arr 中查找值为 key的记录
* 若存在,返回该元素所在的下标;
* 否则,返回 -1
*/
static int binarySearching(int[] arr, int low, int high, int key)
{
int mid;
while(low<=high)
{
mid = ( low + high ) / 2;
if(arr[mid]==key) //找到
return mid;
else if(arr[mid]>key) //在左边部分继续查找
high = mid - 1;
else //在右边部分继续查找
low = mid + 1;
}
return -1;
}
}
}