My code is working for ascending or descending array inputs like 11,12,13,14,15
etc....but it is not working for mixed order array inputs like 11 13 12 15 14
.
import java.util.Scanner;
public class LinearSearch {
public static void main(String[] args) {
int LS[]=new int[100]; //LS is the array
int n,key,flag=0; //n is the number of array elements and key is the element to be searched
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.of array elements");
n=sc.nextInt();
System.out.println("Enter array elements");
for(int i=0;i<n;i++)
LS[i]=sc.nextInt();
System.out.println("Enter element to search");
key=sc.nextInt();
for (int i:LS){
if(LS[i]==key){
flag=1;
System.out.println(key+" is found at location "+(i+1));
}
}
if(flag==0){
System.out.println(key+" is not found");
}
}
}
I think the problem is here: if(LS[i]==key)
you need to change as if(i==key)
because according to for loop for (int i:LS)
i
stands for elements of the array not the index.
If you want to get the index of the element, you can use a for
loop instead of a foreach
loop:
for(int i = 0; i<LS.length; i++) {
if(LS[i]==key){
flag=1;
System.out.println(key+" is found at location "+(i+1));
}
}
One more thing:
You're asking for the number of elements, so it would be a better practice to initialize the array with n
instead of 100
:
int LS[] = new int[n];
When you initialize the array, it allocates the memory according to the size. Think of n
equals to 20
, then it would be a waste to initialize the array with size 100
Otherwise if the user enters a value greater than 100, the program throws ArrayIndexOutOfBoundsException
.