Searching...
Tuesday, 28 February 2017

Binary search algorithm and example

19:41

package
com.vinod.test; /**  * Binary search use to find out the position of the elements for the given key.  *  * The Array should be either in ascending or decending order.  *  *@authorvinodkariyathungalkumaran  *  */ public class BinarySearch { public static void main(String[] args) { int[] arr = { 1, 3, 5, 7, 9, 12, 16, 18 }; System.out.println("Position of 5=" + getPositionUsingBinarySearch(arr, 5)); } /**      * Algorithm      *      *1) First get the array mid position, if mid position of the value equal to the search key will return that one      *      *2) Else if key is less the mid value our start value will be o and end value will be mid -1      *      *3) Else if the key is greater than the mid value we will mark our start value as mid value +1      *      * This activity we will do until the start and end values are equal.      *      *      *@param arr      *@param key      *@return      */ public static int getPositionUsingBinarySearch(int[] arr, int key) { int start = 0; int end = arr.length - 1; while (start <= end) { int mid = (start + end) / 2; if (key == arr[mid]) { return mid; } if (key < arr[mid]) { end = mid - 1; } else { start = mid + 1; } } return -1; } }

0 comments: