View Answers

November 11, 2008 at 4:02 AM

Hi friend,

import java.io.*;

public class BinarySearchDemo {

public static final int NOT_FOUND = -1;

public static <AnyType extends Comparable<? super AnyType>>

int binarySearch(AnyType [] a, AnyType x ){

int low = 0;

int high = a.length - 1;

int mid;

while(low <= high ){

mid = (low + high)/ 2;

if(a[mid].compareTo(x) < 0)

low = mid + 1;

else if(a[mid].compareTo(x) > 0 )

high = mid - 1;

else

return mid;

}

return NOT_FOUND;

}

public static void main(String[]args) throws IOException{

BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Please enter number!");

int SIZE = Integer.parseInt(buff.readLine());

Integer []a = new Integer[SIZE];

for(int i = 0; i < SIZE; i++)

a[i] = i * 2;

for(int i = 0; i < SIZE * 2; i++)

System.out.println("Found " + i + " at " + binarySearch(a, i));

}

}

-----------------------------------------

Read for more information.

http://www.roseindia.net/java/

Thanks.

import java.io.*;

public class BinarySearchDemo {

public static final int NOT_FOUND = -1;

public static <AnyType extends Comparable<? super AnyType>>

int binarySearch(AnyType [] a, AnyType x ){

int low = 0;

int high = a.length - 1;

int mid;

while(low <= high ){

mid = (low + high)/ 2;

if(a[mid].compareTo(x) < 0)

low = mid + 1;

else if(a[mid].compareTo(x) > 0 )

high = mid - 1;

else

return mid;

}

return NOT_FOUND;

}

public static void main(String[]args) throws IOException{

BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Please enter number!");

int SIZE = Integer.parseInt(buff.readLine());

Integer []a = new Integer[SIZE];

for(int i = 0; i < SIZE; i++)

a[i] = i * 2;

for(int i = 0; i < SIZE * 2; i++)

System.out.println("Found " + i + " at " + binarySearch(a, i));

}

}

-----------------------------------------

Read for more information.

http://www.roseindia.net/java/

Thanks.

Related Tutorials/Questions & Answers:

- Java Tutorials
- Java Code example
- Java Programming
- Java Beginners Examples
- Applet Tutorials
- Awt Tutorials
- Java Certification
- Interview Question
- Java Servlets Tutorial
- Jsp Tutorials
- Java Swing Tutorials
- JDBC Tutorial
- EJB Tutorials
- Java Server Faces (JSF) Tutorial
- WAP Tutorial
- Struts Tutorial
- JAXB Tutorial
- Spring FrameWork Tutorial
- SOA&Web Services Tutorials
- Bioinformatics Tutorials
- MySQL Tutorials
- JAVA DOM Tutorial
- XML Tutorial
- EAI Articles
- Many Programming Tutorials Links
- Tutorials Books
**Java Script Tutorial****Ajax Tutorial****Dojo Tutorials****Programming Books****Trainings****Flex****Ant****RDF**