源文件: http://pan.baidu.com/share/link?shareid=439733&uk=3912660076
参考代码来源自课本:
//Main:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LinearSearch { class Program { static void Main(string[] args) { Console.WriteLine("Please enter the array length:"); int length = Convert.ToInt32(Console.ReadLine()); Function obj = new Function(length); int position; Console.WriteLine("The array is:"); Console.WriteLine(obj); while (true) { Console.WriteLine("Please choose:"); Console.WriteLine("1.LinearSearch;"); Console.WriteLine("2.RecursiveLinearSearch;"); Console.WriteLine("3.Exit;"); int number = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(); switch (number) { case 1: Console.WriteLine("Please enter an integer target value:"); int targetValue = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(); position = obj.LinearSearch(targetValue); if (position == -1) Console.WriteLine("The integer {0} was not found.\n", targetValue); else Console.Write( "The integer {0} was found in position:{1}\n", targetValue, position); break; case 2: Console.WriteLine("Please enter an integer target value:"); int targetValue2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(); position = obj.RecursiveLinearSearch(targetValue2,0); if (position == -1) Console.WriteLine("The integer {0} was not found.\n", targetValue2); else Console.Write( "The integer {0} was found in position:{1}\n", targetValue2, position); break; case 3: Environment.Exit(0); break; } } } } }
//Class:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LinearSearch { class Function { /// <summary> /// 声明变量 /// </summary> private int[] array; private static Random ran = new Random(); /// <summary> /// 初始化数组 /// </summary> /// <param name="length"></param> public Function(int length) { array = new int[length]; while (length > 0) array[--length] = ran.Next(0, 100); } /// <summary> /// 线性查找: /// 在数组中从第一个元素开始依次向后和给定的元素比较找到返回位置, /// 否则说明没有找到。 /// 核心算法时间复杂度: /// T(n)=O(n); /// </summary> /// <param name="targetValue"></param> /// <returns></returns> public int LinearSearch(int targetValue) { int position = -1; int index = 0; while (index < array.Length) { if (targetValue != array[index++]) position = -1; else return position = index - 1; } return position; } /// <summary> /// 递归算法 /// </summary> /// <param name="targetValue"></param> /// <param name="index"></param> /// <returns></returns> public int RecursiveLinearSearch(int targetValue, int index) { int position = -1; if (index < array.Length) { if (targetValue != array[index]) position = RecursiveLinearSearch(targetValue, ++index); else return position = index; } return position; } /// <summary> /// 输出. /// </summary> /// <returns></returns> public override string ToString() { string temporary = string.Empty; foreach (int element in array) temporary += element + " "; return temporary += "\n"; } } }
//运行结果截图