Binary Search using Java
It is a technique to search an element in sorted array. In this type of search half of the array is ignored just after one comparison. Each time required element is compared with middle element of the array and range is decided .
Best Case Performance : O(1)
Average Case Performance : O(log n)
Worst Case Performance : O(log n)
Demo Output:
The Program
Found bugs, please do let me know by commenting here !
Best Case Performance : O(1)
Average Case Performance : O(log n)
Worst Case Performance : O(log n)
Demo Output:
The Program
import java.util.Scanner; public class BinarySearch1 { public static void main(String args[]) { int i, first=0, last, mid, no, element; Scanner s = new Scanner(System.in); System.out.println("\n How many elements:"); no= s.nextInt(); int arr[]= new int[no]; System.out.println("\n Enter the elements:"); for (i = 0; i < no; i++) arr[i] = s.nextInt(); System.out.println("\n Enter the element to be searched:"); element = s.nextInt(); last = no - 1; mid = (first + last)/2; while( first <= last ) { if ( arr[mid] < element ) first = mid + 1; else if ( arr[mid] == element ) { System.out.println(element+" found...! " +"at position : \t"+ (mid + 1)); break; } else last = mid - 1; mid = (first + last)/2; } if ( first > last ) System.out.println("Required element is not found in the list.\n"); } }
Found bugs, please do let me know by commenting here !
Comments
Post a Comment