我有一些对我来说没有多大意义的代码。我有一个字符串数组,我正在使用二进制搜索在 foreach() 循环中对它们进行计数。除了排序之外,我尝试输出的代码都完全相同。我不确定为什么我会得到我得到的结果。我认为它应该两次都以相同的方式计算数组值。有什么帮助吗?
代码:
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);
}
}
输出:
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
我敢肯定这完全是愚蠢的,但我无法弄清楚。