Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Array.BinarySearch() giving negative numbers?

Tags:

c#

I have some code that isn't making much sense to me. I have an array of strings and I'm using a binary search to count them in a foreach() loop. The code is exactly the same both times I attempt output, other than sorting. I'm not sure why I'm getting the results I'm getting. I assume it should just count the array values the same way both time. Any help?

Code:

using System;
public class Driver {
    public static void Main(string [] args) {
        String [] s = {"Bob", "Jane", "Will", "Bill", "Liz"};

        Console.WriteLine("Before Sorting:\n----------");
        foreach(string item in s) {
            Console.WriteLine("{0}. {1}", Array.BinarySearch(s, item) + 1, item);
        }
        Console.WriteLine("Will is at position {0}", Array.BinarySearch(s, "Will") + 1);

        Console.WriteLine("\n\nAfter Sorting:\n----------");
        Array.Sort(s);
        foreach(string item in s) {
            Console.WriteLine("{0}. {1}", Array.BinarySearch(s, item) + 1, item);
        }
        Console.WriteLine("Will is at position {0}", Array.BinarySearch(s, "Will") + 1);
    }
}

Output:

Before Sorting:
----------
1. Bob
2. Jane
3. Will
0. Bill
-2. Liz
Will is at position 3

After Sorting:
----------
1. Bill
2. Bob
3. Jane
4. Liz
5. Will
Will is at position 5

I'm sure it's something entirely stupid, but I can't figure it out.

like image 788
will Avatar asked Oct 03 '12 17:10

will


2 Answers

Binary search only works on sorted arrays. It is not finding the value:

If value is not found and value is less than one or more elements in array, a negative number which is the bitwise complement of the index of the first element that is larger than value. If value is not found and value is greater than any of the elements in array, a negative number which is the bitwise complement of (the index of the last element plus 1).

like image 88
CrazyCasta Avatar answered Oct 07 '22 21:10

CrazyCasta


Array.BinarySearch requires that the array be sorted. From the documentation:

This method does not support searching arrays that contain negative indexes. array must be sorted before calling this method.

It will return negative values, by design:

If value is not found and value is less than one or more elements in array, a negative number which is the bitwise complement of the index of the first element that is larger than value.

like image 27
Reed Copsey Avatar answered Oct 07 '22 21:10

Reed Copsey