how does binary search work code example

Example 1: binary search

import java.util.Scanner;

public class Binarysearch {

	public static void main(String[] args) {
		int[] x= {1,2,3,4,5,6,7,8,9,10,16,18,20,21};
		Scanner scan=new Scanner(System.in);
		System.out.println("enter the key:");
		int key=scan.nextInt();
		int flag=0;
		int low=0;
		int high=x.length-1;
		int mid=0;
		while(low<=high)
		{
			mid=(low+high)/2;
			if(keyx[mid])
			{
				low=mid+1;
			}
			else if(key==x[mid])
			{
				flag++;
				System.out.println("found at index:"+mid);
				break;
			}
		}
		if(flag==0)
		{
			System.out.println("Not found");
		}
		

	}

}

Example 2: Implement a binary search of a sorted array of integers Using pseudo-code.

# Here's the pseudocode for binary search, modified for searching in an array. The inputs are the array, which we call array; the number n of elements in array; and target, the number being searched for. The output is the index in array of target:

    1.Let min = 0 and max = n-1.
    2. Compute guess as the average of max and min, rounded down (so that it is an integer).
    3. If array[guess] equals target, then stop. You found it! Return guess.
    4. If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
    5. Otherwise, the guess was too high. Set max = guess - 1.
    6. Go back to step 2.

Example 3: binary search

//Binary search can apply to sorted data only.
//Time complexity of binary search is O(log n ).
//It always divide the whole data in parts and compare  a search key to middle element only.


import java.util.*;
public class BinarySearch {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int[] a = {10,20,50,30,40};
		int key=sc.nextInt();
		
		Arrays.sort(a);					// An method in java.util.Arrays package to sort an array element.
		
		int first=0,end=a.length-1,mid=0,flag=0;

		while(first<=end)
		{
			mid=(first+end)/2;
			if(keya[mid])		   // Move to right part if key is greater than middle element.
			{
				first = mid+1;
			}
			else
			{
				flag=1;
				break;
			}
		}
		if(flag==1)
		{
			System.out.println("Success! found");
		}
		else
		{
			System.out.println("Error! This key (" + key + ") does not exist in the array");
		}
		
	}

}

Tags:

Misc Example