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.