Friday, August 28, 2009

Finding an Element in a Sorted Array using Java

Arrays is Java Class which provides various methods for manipulating arrays (such as sorting and searching).

Sorting using Arrays :

Arrays.sort(srcArray)  sorts all the elements present in the array. By Default it sorts elements in ascending order where srcArray is source Array on which sorting will appy.

Binary Search using Arrays :
Arrays.binarySearch(srcArray, element) - searches the element in the specified source array in the way of binary search. Binary Search takes more less time than the index search or the sequential search.

If element is present in given array then method binarySearch returns index of matched element in source Array. and return -1 if element is not present in Array

Sorting Array in Java :
int src[] = {1,6,-2,0,5,12};        
Find an Element in Sorted Array using Java :
int index = Arrays.binarySearch(src,6);
System.out.println("index of searched Element - " + index);        
index = Arrays.binarySearch(src,-10);
System.out.println("index of searched Element - " + index);

Printing Array Elements using Java:
static void printArray(int arr[]) {
    for (int i = 0; i < arr.length; i++) {
       System.out.print(arr[i] + ", ");
Output :
Array after Sorting - -2, 0, 1, 5, 6, 12, 
index of searched Element - 4
index of searched Element - -1

No comments:

Post a Comment