Tuesday, September 13, 2011

Find out location of a list element using BinarySearch


//How to find out location of a list element using BinarySearch
//UseBinarySearchExample.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UseBinarySearchExample
{
public static void main(String arg[])
{
List ls = new ArrayList();
ls.add("Bappa");
ls.add("Tarun");
ls.add("Arun");
ls.add("Arup");
ls.add("Barun");
ls.add("Milan");

List li = new ArrayList();
li.add(23);
li.add(25);
li.add(27);
li.add(22);
li.add(29);
li.add(29);

int i= Collections.binarySearch(li,25);
System.out.println("25 location is: "+i);

int s= Collections.binarySearch(ls,"Barun");
System.out.println("Barun's location is "+s+"th");
}
}

Output =>
25 location is: 1
Barun's location is 4th

No comments:

Post a Comment