Sunday, February 12, 2017

Java Program to search an element in an String/Object Array.

Note:- To search an element in an array elements must be sorted before search otherwise we will get
unpredictable result. because java.util.Arrays uses binary search mechanism.
If element is found then it will return its index value and if element is not found then it
will return insertion point(Insertion point is a place where we can place target element
in sorted list.
Note:- Index starts from 0 to (n-1) . But Insertion point starts from -1 to -(n+1).
if there are 3 elements in an array then index will be 0-2.
and insertion point may be -1 to -4.
*/

import static java.lang.System.out;
import java.util.Arrays;
class SearchArray2
{
static public void main(String...alt)
{
String[] s={"anil","ravi","ali","ram","mohan","anthony"};
out.println("Before Sorting : ");
for(String x:s)
out.print(x+"  ");
Arrays.sort(s); // Default natural sorting(Alphabetical Order)
out.println("\nAfter Sorting : ");
for(String x:s)
out.print(x+"  ");
int result1=Arrays.binarySearch(s,"ram");
out.println("\n\nram is available in index : "+result1);
int result2=Arrays.binarySearch(s,"rama");
out.println("rama is not available So its insertion point is : "+result2);
}
}

Share this

0 Comment to "Java Program to search an element in an String/Object Array."

Post a Comment