Binary Search program in Java

//Here you basically take three pointers one at the start of the array one at the end and one at the mid.

//Then compare with the element to be found if greater then increment the start to mid+1 and less then

//decrement the end to mid -1. Keep going on until start not equal to end.

public class arrayserach {

 

int[]  array = {1,2,3,4,5,6,7,8,9,12,34,345,462,545,777,778,999,1001,1002,1111,1112,1113};

int start, end , mid, count;

 

public arrayserach(){

 

 

start = 0;

end = array.length – 1;

mid = (array.length/2) – 1;

count = 0;

}

 

public int search(int i)

{

 

while(start != end)

{

count++;

if(i ==array[start])

{

System.out.println(“Found num: “+i+ “at index: “+start);

System.out.println(count);

return 1;

}

 

if(i == array[end]){

System.out.println(“Found num: “+i+”at index: “+end);

System.out.println(count);

return 1;

 

}

 

if(i == array[mid]){

System.out.println(“Found num”+i+”at index: “+mid);

System.out.println(count);

return 1;

}

 

if(array[mid] > i)

{

end = mid -1;

mid = (start + end) / 2;

continue;

}

if(array[mid] < i)

{

start = mid +1;

mid = (start + end) /2;

continue;

}

}

if(array[end] == i){

System.out.println(“Found”);

System.out.println(count);

return 1;

}

return count;

}

 

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s