Binary search works faster than sequential search.It search on sorted elements.
In Binary Search, Let's say You have an array and you want to search specific item in array
How it Works :
Java Program for Binary Search Algorithm :
Output
Searching for Item in sorted Array: 12
The index of 12 is : 6
In Binary Search, Let's say You have an array and you want to search specific item in array
How it Works :
- Initialize low=0 and high as max length of search array - 1.
- while low<=high each item you, take middle element of array and if given searchItem is less than middle element then you need to search in array of elements array which are less than middle element. Hence, high = middle - 1
- If given searchItem is larger than middle element then search in array of elements which are greater than middle element. Hence low = middle+1
- If searchItem == middle element then you have found your element.
Java Program for Binary Search Algorithm :
package com.anuj.algorithms; import java.util.Arrays; /** * * @author Anuj Patel * */ public class BinarySearch { public static void main(String[] args) { BinarySearch bs = new BinarySearch(); int a[] = { 1, 2, 3, 4, 5, 7, 17, 19, 12 }; int searchItem = 12; Arrays.sort(a); System.out.println("Searching for Item in sorted Array: " + searchItem); //int searchResult = Arrays.binarySearch(a, searchItem); int searchResult = bs.search(a, searchItem); System.out.println("The index of " + searchItem + " is : "+ searchResult); } /** * Binary Search Algorithm * * @param a * @param searchItem * @return index of searchItem */ public static int search(int[] a, int searchItem) { int low = 0; int high = a.length - 1; while (low <= high) { int middle = (low + high) / 2; // int middle = (low+high) >>> 1; int midVal = a[middle]; if (searchItem > midVal) { low = middle + 1; } else if (searchItem < midVal) { high = middle - 1; } else { return middle; } } return -(low + 1); } }
Output
Searching for Item in sorted Array: 12
The index of 12 is : 6
No comments:
Post a Comment