Search This Blog

Saturday, February 4, 2012

Searching Algorithm :

Besides sorting, the Collections and Arrays classes provide a mechanism to search a List or an array, as well as to find the first and last values within a Collection. The binarySearch algorithm searches for a specified element in a sorted List. This algorithm takes a List and an element to search for the search key. This form assumes that the List is sorted in ascending order according to the natural ordering of its elements.

Before searching an element, the List must be sorted, Once you have sorted the List, using Collection.sort( ) method, you can perform a quickly binary search operation using the overridden binarySearch( ) method.

For example, the following program prints the sorted arguments list (the arguments, given through command line) and then search the position of a specified key value.

import java.util.*;

public class SearchDemo {
public static void main(String[] args) {
try{
List list = Arrays.asList(args);
Collections.sort(list);
System.out.println("The sorted list is: "+list);
int pos = Collections.binarySearch(list, list.get(2));
System.out.println("The position of the searched element is : "+pos
+
" and the element is:"+list.get(2));
}
catch(Exception e){}

}
}

Output of this program:

C:\nisha>java SearchDemo this is a commandline argument
The sorted list is: [a, argument, commandline, is, this]
The position of the searched element is : 2 and the element is:commandline

C:\nisha>

No comments:

Post a Comment