The array must be sorted in order for the binary search to return results. When you call reverse, the array is no longer in sorted order, so the result of the search is a nonsensical result.
On Apr 29, 2:11 am, Jingle <[email protected]> wrote: > And I fond that when I don't Sort() first, > al.AddRange ... > al.Reverse(); > Console.WriteLine(al.BinarySearch("this")); > displays 2, a right number. > What have the Sort() and Reverse() done with the ArrayList? > > Can anyone tell some inner mechanism about this? > Thx. > > On 4月27日, 下午5时41分, Jingle <[email protected]> wrote: > > > Thank you for the answer. > > But Why The > > > al.AddRange ... > > al.Sort(); > > al.Reverse(); > > Console.WriteLine(al.BinarySearch("this")); > > displays -7 > > > al.AddRange ... > > al.Sort(); > > al.Reverse(); > > al.Reverse(); > > Console.WriteLine(al.BinarySearch("this")); > > displays 4 ? > > The different is just one more al.Reverse(). > > > On 4月27日, 下午4时47分, Jamie Fraser <[email protected]> wrote: > > > > Generally when using a BinarySort, a negative number indicates that > > > the element wasn't found. The reason for the negative -X rather than > > > -1 is because the sort returns the element it "got to" during its > > > search before it realised that the element wasn't present. > > > > On Tue, Apr 27, 2010 at 3:25 AM, Jingle <[email protected]> wrote: > > > > Hi All, > > > > I'm learning MCTS 70-536. These are some codes from Chapter 4: > > > > > ArrayList al = new ArrayList(); > > > > al.AddRange(new string[] { "Hello", "world", "this", "is", "a", > > > > "test" }); > > > > Console.WriteLine(al.BinarySearch("this")); > > > > > It displays 2 . but when I change the code to this: > > > > > ArrayList al = new ArrayList(); > > > > al.AddRange(new string[] { "Hello", "world", "this", "is", "a", > > > > "test" }); > > > > al.Sort(); > > > > al.Reverse(); > > > > Console.WriteLine(al.BinarySearch("this")); > > > > > It displays -7 . (yet when I add one more "al.Reverse()" into the > > > > code, it displays 4 ) > > > > > I've tested that only the code above gets a nagative number, other > > > > groups by some "al.Sort" and some "al.Reverse" all display a right > > > > number. > > > > Anyone who can help to explain ? Thanks! > > > > > -- > > > > Subscription > > > > settings:http://groups.google.com/group/dotnetdevelopment/subscribe?hl=en
