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.