本文介绍了二进制搜索类:检索有序数组中最后一个元素的小问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 你好, 我有一个字符串数组,需要找到匹配的字符串和 最快的代码。我决定订购数组,然后写一个二进制的 搜索算法。 我想出的是以下内容。我注意到如果我设置: int upper = strings.GetUpperBound(0); 我永远不会匹配数组中的最后一个元素(即iii) 如果我设置: int upper = strings.GetUpperBound(0)+ 1; 我也能匹配数组中的最后一个元素。 问题是我认为上层应该等于 strings.GetUpperBound(0)。 有什么我想念的吗?算法是错误的还是遗漏了什么??? 使用系统; 命名空间TestApplication { class BinarySearchClass { static void Main(string [] args) { string [] strings = new string [] {" aaa"," bbb"," ccc"," ddd"," eee"," fff", " ggg", " hhh"," iii"}; BinarySearchClass search = new BinarySearchClass(); int res = search.FindString(字符串,iii); Console.Read(); } public int FindString (string [] strings,string str) { int lower = strings.GetLowerBound(0); int upper = strings.GetUpperBound (0); 返回this.BinarySearch(字符串,str,lower,upper); } public int BinarySearch(string [] strings,string str,int lowerbound,int upper绑定) { int pos =((上限 - 下限)/ 2)+下限; int res = string 。比较(字符串[pos],str); if(res 0) { pos = this.BinarySearch (strings,str,lowerbound,pos); } else if(res< 0) { pos = this.BinarySearch(strings,str,pos,upperbound); } 返回pos; } } } 问候, Bob Rock Hello, I have an array of strings and need to find the matching one with thefastest possible code. I decided to order the array and then write a binarysearch algo.What I came up with is the following. I noticed that if I set: int upper = strings.GetUpperBound(0); I never match the last element in the array (i.e. "iii") while if I set: int upper = strings.GetUpperBound(0) + 1; I''m able to match also the last element in the array.The problem is that I think upper should indeed be equal tostrings.GetUpperBound(0).Is there something I''m missing??? Is the algo wrong or missing something???using System; namespace TestApplication{class BinarySearchClass{static void Main(string[] args){string[] strings = new string[]{"aaa", "bbb", "ccc", "ddd", "eee", "fff","ggg", "hhh", "iii"}; BinarySearchClass search = new BinarySearchClass(); int res = search.FindString(strings, "iii"); Console.Read();} public int FindString(string[] strings, string str){int lower = strings.GetLowerBound(0);int upper = strings.GetUpperBound(0); return this.BinarySearch(strings, str, lower, upper);} public int BinarySearch(string[] strings, string str, int lowerbound, intupperbound){int pos = ((upperbound - lowerbound) / 2) + lowerbound; int res = string.Compare(strings[pos], str); if(res 0){pos = this.BinarySearch(strings, str, lowerbound, pos);}else if(res < 0){pos = this.BinarySearch(strings, str, pos, upperbound);}return pos;}}} Regards,Bob Rock 推荐答案 鲍勃,这个怎么样.. int pos = Array.BinarySearch< ; string>(字符串," iii"); JW Bob, how about this.. int pos= Array.BinarySearch<string>(strings, "iii"); J.W. 这篇关于二进制搜索类:检索有序数组中最后一个元素的小问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-24 22:46