折半查找(C#数据结构学习六)
1using System;
2using System.Collections.Generic;
3using System.Text;
4
5namespace SoloDataStructure
6{
7
8 public class BinschDemo
9 {
10 public static int Binsch(int[] a,int key)
11 {
12 int low = 1;
13 int high = a.Length;
14 while (low <= high)
15 {
16 int mid=(low+high)/2;
17 if (key == a[mid])
18 {
19 return mid; //返回找到的索引值
20 }
21 else
22 {
23 if (key < a[mid])
24 high = mid - 1;
25 else
26 low = mid + 1;
27 }
28 }
29 return 0; //查找失败
30
31
32 }
33 static void Main(string[] args)
34 {
35
36 int[] list=new int[10];
37 for (int i = 0; i < 10; i++)
38 {
39 Console.Write("input 10 number,here is the{0}th number :",i);
40 list[i] =Convert.ToInt32(Console.ReadLine());
41 }
42
43 Console.Write("Ok!Find a number in the list:");
44 int find = Console.Read();
45 int result = Binsch(list,find);
46 Console.WriteLine(result);
47 Console.ReadLine();
48
49 }
50 }
51}
2using System.Collections.Generic;
3using System.Text;
4
5namespace SoloDataStructure
6{
7
8 public class BinschDemo
9 {
10 public static int Binsch(int[] a,int key)
11 {
12 int low = 1;
13 int high = a.Length;
14 while (low <= high)
15 {
16 int mid=(low+high)/2;
17 if (key == a[mid])
18 {
19 return mid; //返回找到的索引值
20 }
21 else
22 {
23 if (key < a[mid])
24 high = mid - 1;
25 else
26 low = mid + 1;
27 }
28 }
29 return 0; //查找失败
30
31
32 }
33 static void Main(string[] args)
34 {
35
36 int[] list=new int[10];
37 for (int i = 0; i < 10; i++)
38 {
39 Console.Write("input 10 number,here is the{0}th number :",i);
40 list[i] =Convert.ToInt32(Console.ReadLine());
41 }
42
43 Console.Write("Ok!Find a number in the list:");
44 int find = Console.Read();
45 int result = Binsch(list,find);
46 Console.WriteLine(result);
47 Console.ReadLine();
48
49 }
50 }
51}