我是新来编程。我有六个月认为,我已经开始学习编程,我想测试我自己的一些算法。我想实现二进制搜索算法。从理论上讲我已经掌握的概念,但在执行我有一些麻烦。
下面是算法的实现:
public static boolean binarySearchNumber(int[] numbers, int number) {
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
int lowIndex = 0;
int highIndex = numbers.length;
while(lowIndex!=highIndex) {
int midIndex = (lowIndex+highIndex)/2;
if(numbers[midIndex]==number) {
return true;
} else if(numbers[midIndex]>number) {
lowIndex = midIndex+1;
} else if(numbers[midIndex]<number) {
highIndex = midIndex-1;
}
}
return false;
}
单元测试
@Test
public void testBinarySearchNumber() {
// setup
int[] numbers = new int[] { 1, 3, 55, 8, 22, 9, 11, 0 };
// execute
boolean found = ArrayUtil.binarySearchNumber(numbers, 8);
System.out.println(found);
}
先感谢您。
超越了其他的答案中报告的错误,我发现了另一个问题:
public static boolean binarySearchNumber(int[] numbers, int number) {
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
int lowIndex = 0;
int highIndex = numbers.length;
while (lowIndex != highIndex) {
int midIndex = (lowIndex + highIndex) / 2;
if (numbers[midIndex] == number) {
return true;
} else if (numbers[midIndex] < number) {
lowIndex = midIndex + 1;
} else if (numbers[midIndex] > number) {
highIndex = midIndex ; // here
}
}
return false;
}
midIndex
在阵列中,你不需要减1,否则你将永远有一个元素少。
编辑
以达到预期的效果另一种方式是改变,如果条件由@伊兰的答案的建议。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句