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 }

转载于:https://www.cnblogs.com/smilence/archive/2011/04/12/Joassa.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值