一个简单的二分算法

 //首先已知一组数,然后查找里面是否还有你想要的数字,如果这组数全部加载到内存中,消耗的内存在你的承受范围内,那么就可以先对这组数进行排序,然后在查找。如果这组数很大,那么你就必须把这组数分开到不同的文件中,然后逐个文件进行处理
1
class Program 2 { 3 static void Main(string[] args) 4 { 5 int[] iarray = new int[] { 2, 6, 4, 98, 5, 16, 9, 8, 7, 44 }; 6 sort(iarray); 7 try 8 { 9 Console.WriteLine(search(iarray)); 10 } 11 catch 12 { 13 Console.WriteLine("This num is not in this Array or you enter an invalid num!"); 14 } 15 Console.ReadKey(); 16 17 } 18 static int search(int[] array) 19 { 20 int low = 0; 21 int high = array.Length - 1; 22 Console.WriteLine("Please input a number:"); 23 int i = int.Parse(Console.ReadLine()); 24 while (low <= high) 25 { 26 int middle = (low + high) / 2; 27 if (i == array[middle]) 28 { 29 return i; 30 } 31 else if (i < array[middle]) 32 { 33 high = middle - 1; 34 } 35 else 36 { 37 low = middle + 1; 38 } 39 } 40 throw new Exception(); 41 } 42 static void sort(int[] array) 43 { 44 45 for (int i = 1; i < array.Length; i++) 46 { 47 for (int j = 0; j < array.Length - i; j++) 48 { 49 if (array[j] > array[j + 1]) 50 { 51 int tempt = array[j]; 52 array[j] = array[j + 1]; 53 array[j + 1] = tempt; 54 } 55 } 56 } 57 } 58 59 }
posted @ 2012-09-14 22:19  饮酒笑红尘  Views(182)  Comments(0Edit  收藏  举报