Binary Search Algorithm in Java source code
Description
Find the position of specific input value within a sorted array (either descending/ascending).The algorithm compares the key value with the middle value of array, if the key matches it will return the value or other wise returns -1 value.
Time complexity for binary
Worst : O (log n)
Average : O (log n)
Binary Search Algorithm Computation |
int []values = {1,2,5,6,12,25,26,27,30}; // sorted array
/**
* Binary Search algorithm or Half interval search algorithm implementation
* Find the position of a specific value (key) from/within a sorted array
*/
package com.blogspot.javabelazy.logics;
/**
* @author javabelazy
*
*/
public class BinarySearch {
private static int attempt = 0;
private int findIndex(int[] values, int target) {
return binarySearch(values,target,0,values.length-1);
}
private int binarySearch(int[] values, int target, int start, int end) {
attempt = attempt +1;
if(start > end){
return -1;
}
int middle = (int) Math.floor((start+end)/2);
int value = values[middle];
if (value > target) { return binarySearch(values, target, start, middle-1); }
if (value < target) { return binarySearch(values, target, middle+1, end); }
return middle;
}
/**
* @param binsearchalgo string
*/
public static void main(String[] binsearchalgo) {
int []values = {1,2,5,6,12,25,26,27,30}; // sorted array
int target = 27; // value to be find (the key in binary search algorithm)
BinarySearch binarySearch = new BinarySearch();
int position = binarySearch.findIndex(values,target);
System.out.println(" Size of the array to search : "+values.length);
System.out.println(" Value to be found : "+target);
System.out.println(" Position of the value found : "+position);
System.out.println(" Attempt made in finding value : "+attempt);
System.out.println(" www.javabelazy.blogspot.in ");
}
}
Output
http://javabelazy.blogspot.in/
I loved as much as you'll receive carried out right here.
ReplyDeleteThe sketch is tasteful, your authored subject matter stylish.
nonetheless, you command get got an shakiness over that you
wish be delivering the following. unwell unquestionably come further formerly again since exactly the
same nearly very often inside case you shield this increase.