我写了这段代码,它总是显示相同的结果为什么?代码是一种搜索方法.
using System; using System.Collections.Generic; using System.Text; namespace CArraySe { class Program { class CArray { private int[] arr; private int upper; private int numElements; private int compCount; public CArray(int size) { arr = new int[size]; upper = size - 1; numElements = 0; compCount = 0; } public void Insert(int item) { arr[numElements] = item; numElements++; } public void DisplayElements() { for (int i = 0; i <= upper; i++) { Console.Write(arr[i]); if (i == upper) { Console.WriteLine(); continue; } Console.Write(", "); } } public void Clear() { for (int i = 0; i <= upper; i++) arr[i] = 0; numElements = 0; } public bool SeqSearch(CArray n, int sValue) { for (int index = 0; index < n.upper; index++) { if (arr[index] == sValue) return true; } compCount++; return false; } public int binSearch(CArray n, int value) { int upperBound, lowerBound, mid; upperBound = n.upper; lowerBound = 0; while (lowerBound <= upperBound) { mid = (upperBound + lowerBound) / 2; if (arr[mid] == value) return mid; else if (value < arr[mid]) upperBound = mid - 1; else lowerBound = mid + 1; } compCount++; return -1; } static void Main(string[] args) { CArray nums = new CArray(10); Random rnd = new Random(100); for (int i = 0; i < 10; i++) nums.Insert((int)(rnd.NextDouble() * 100)); Console.WriteLine(); Console.Write("The Binary Search Result is: "); Console.WriteLine(nums.binSearch(nums, 500)); Console.WriteLine(nums.compCount); nums.Clear(); for (int i = 0; i < 10; i++) nums.Insert((int)(rnd.NextDouble() * 100)); Console.Write("The Sequential Search result is: "); Console.WriteLine(nums.SeqSearch(nums, 500)); Console.WriteLine(nums.compCount); } } } }
即使我改变了我正在寻找的数字,它也始终显示相同的结果.
输出是:
The Binary Search Result is: -1 1 The Sequential Search result is: False 2 Press any key to continue . . .
crashmstr.. 8
我认为没有找到您搜索的值(500).尝试输出nums数组并验证您要查找的内容是否在数组中.
另外,一个搜索返回一个int而另一个返回一个bool.有具体原因吗?
编辑:此外,二进制搜索仅适用于排序列表.
我认为没有找到您搜索的值(500).尝试输出nums数组并验证您要查找的内容是否在数组中.
另外,一个搜索返回一个int而另一个返回一个bool.有具体原因吗?
编辑:此外,二进制搜索仅适用于排序列表.