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 SearchArray
{
static public void main(String...alt)
{
Double[] a={10.6,15.3,10.5,2.3,6.4,1.7,9.78,2.34};
out.println("Before Sorting : ");
for(double x:a)
out.print(x+" ");
Arrays.sort(a); // Default natural sorting(Ascending Order)
out.println("\nAfter Sorting : ");
for(double x:a)
out.print(x+" ");
int result=Arrays.binarySearch(a,6.4);
out.println("\n\n6.4 is available in index : "+result);
int result2=Arrays.binarySearch(a,6.5);
out.println("6.5 is not available So its insertion point is : "+result2);
}
}
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 SearchArray
{
static public void main(String...alt)
{
Double[] a={10.6,15.3,10.5,2.3,6.4,1.7,9.78,2.34};
out.println("Before Sorting : ");
for(double x:a)
out.print(x+" ");
Arrays.sort(a); // Default natural sorting(Ascending Order)
out.println("\nAfter Sorting : ");
for(double x:a)
out.print(x+" ");
int result=Arrays.binarySearch(a,6.4);
out.println("\n\n6.4 is available in index : "+result);
int result2=Arrays.binarySearch(a,6.5);
out.println("6.5 is not available So its insertion point is : "+result2);
}
}
0 Comment to "Java Program to search an element in a Double/Object Array."
Post a Comment