Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Java
import java.util.Scanner;
 
class BinarySearch 
{
  public static void main(String args[])
  {
    int c, first, last, middle, n, search, array[];
 
    Scanner in = new Scanner(System.in);
    System.out.println("Enter number of elements");
    n = in.nextInt(); 
    array = new int[n];
 
    System.out.println("Enter " + n + " integers");
 
 
    for (c = 0; c < n; c++)
      array[c] = in.nextInt();
 
    System.out.println("Enter value to find");
    search = in.nextInt();
 
    first  = 0;
    last   = n - 1;
    middle = (first + last)/2;
 
    while( first <= last )
    {
      if ( array[middle] < search )
        first = middle + 1;    
      else if ( array[middle] == search ) 
      {
        System.out.println(search + " found at location " + (middle + 1) + ".");
        break;
      }
      else
         last = middle - 1;
 
      middle = (first + last)/2;
   }
   if ( first > last )
      System.out.println(search + " is not present in the list.\n");
  }
}


What I have tried:

I found it in the net and I want to know the explanation of it's algorithm.
Posted
Updated 8-Mar-16 2:13am
v2
Comments
CHill60 8-Mar-16 5:45am    
Why not go back to where you found it and ask the author?
You are unlikely to get anyone else to go through the program explaining it line by line - it could take quite a long time... we don't get paid for doing this!
Richard MacCutchan 8-Mar-16 6:18am    
It's a binary chop search. Like a Barnsley chop but not as much fun.
Kurukuruchi 8-Mar-16 6:30am    
I see. ayy sir can i ask you about its algorithm? i dont understand the uses of every codes
Richard MacCutchan 8-Mar-16 6:31am    
Go to Google and type "binary chop". You will get lots of useful information.
Kurukuruchi 8-Mar-16 6:38am    
okie.thanks

It's a trivial binary chop: Binary search algorithm - Wikipedia, the free encyclopedia[^] - and frankly, if you can't work it out from that simple code, then you need to go back to your course notes and start reading from the begining again.
This is trivial stuff. If you don't understand this, then the next exercise your tutor gives you is going to be nearly impossible...
 
Share this answer
 
This program is supposed to be about binary search (look at the link in OriginalGriff's solution.

This program have a fail because binary search works only on ordered/sorted array, and the program don't sort the array.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900