Write a ava pogram to find the index of a specific number kin an unsorted array. If the number is repeated more than once print the index of first
occurrence of an element
Answers
Answer:
Explanation:
Binary search can also be used to find the index of the array element in an array. But the binary search can only be used if the array is sorted.Java provides us with an inbuilt function which can be found in the Arrays library of Java which will rreturn the index if the element is present, else it returns -1. The complexity will be O(log n). Below is the implementation of Binary search
import java.util.";
public class Index {
public static void main(String args[]) {
Scanner sc-new Scanner(System.in);
int i,search,n;
boolean x-true;
System.out.print("How many elements? ");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter them..");
for(i=0;i<n;i++) {
System.out.print("a["+i+"] = ");
a[i]=sc.nextInt();
}
Arrays.sort(a);
System.out.println("Sorted Array: "+Arrays.toString(a));
System.out.print("Enter the element to be
searched for: ");
search=sc.nextInt();
for(i=0;i<n;i++) {
if(a[i]==search) {
System.out.println("Position: "+i);
x=false;
break;
}
}
if(x)
System.out.println("Not found in the
array.");
sc.close();
}
}