v_anon :
I am new to programming. I have six month that i have started learning programming and i trying to test my self with some algorithm. I am trying to implement the binary search algorithm. In theory I have grasped the concept but in implementation i am having some trouble.
Below is the algorithm implementation:
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;
}
The unit test
@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);
}
Thank you in advance.
Renato :
beyond the error reported in the other answers, I found another one:
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
is in array, you don't need to subtract 1, otherwise you will always have one element less.
EDIT
Another manner to achieve the desired results is change the if condition as suggested by @Eran's answer.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=415914&siteId=1