9:14 am - Wednesday December 19, 2018

Java Example Program for Binary search

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

/**
*@Author : Candidjava.com
*@Description : Example for Binary search ()
*/
public class FindnoBinarySearch {
public void BinarySearch(int a[], int t) {
int low = 1;
int high = a.length; // find the length of array and assign into high
int mid;
mid = low + ((high - low) / 2); // find the middle position and assign
// into mid
if (high < low) // if high lower than low,there is no array element
{
System.out.println("Array is not fonud");
}
for (low = 1; low < high; low++) // looping upto number of elements in
// array
{
if (a[mid] < t) // if t is greaterthan a[mid],increase one in the
// mid value
{
mid = mid + 1;
} else if (a[mid] > t) // if t is lessthan a[mid],decrease one in
// the mid value
{
mid = mid - 1;
} else if (a[mid] == t) // if t is equalto a[mid],The targeted
// element is mid element
{
System.out.println("Target number " + t + " is found");
break; // if Target element is found,break this loop and control
// goes to next statment
}
}
}

public static void main(String[] args) {
int[] a = { 0, 2, 8, 12, 15, 19, 24, 76, 79, 80 };
FindnoBinarySearch b = new FindnoBinarySearch();
b.BinarySearch(a, 24);
}
}

Output :

Target number 24 is found

Filed in: Z-A All Java Codes

Comments are closed.