今天写了一段关于查找在int[] 数组中某个值下标的程序:
public class ConsumerCredit {
private static int[] credits = {18,25,7,36,13,2,89,63} ;
public static void main(String args[])
{
System.out.print("最小的积分是:");
int min = new ConsumerCredit().sortCredits(credits)[0];
System.out.println(min) ;
int pos = Arrays.binarySearch(credits,2);
System.out.println("在数组中的原始位置是:" + pos);
}
private int[] sortCredits(int[] credits)
{
Arrays.sort(credits) ; // 对积分排序
return credits ;
}
}
pos的结果总是不确定,因为思维定势,太相信自己的记忆,自认为这样写是正确的。最后实在耐不住,认真看了下API文档,释然:
Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found
索引之前必须排序,必须排序啊,亲!这样才能得到正确的结果。记住了。。。
本文探讨了在编程中查找数组中特定值下标时,排序数组的重要性,并通过实例展示了未排序数组可能导致的不确定性结果。文章强调了API文档阅读对于避免编程错误的必要性。
3804

被折叠的 条评论
为什么被折叠?



