Linear search process starts comparing the search element with the first element in the given list if both are match then result is element found otherwise search element is compared with the next element in the given list repeat the process until the search element is compared with the last element in the given list the last element also doesn't match then the result is element is not found in the list that means the search element is compared with element by element in the list
Example
A[6] = [65] [20] [10] [55] [32] [12]
A[0] A[1] A[2] A[3] A[4] A[5]
Let the search element to be 12
Step 1:-search element is compared with first element 65
A[6] = [65] [20] [10] [55] [32] [12]
A[0] A[1] A[2] A[3] A[4] A[5]
12
Both are not matching so move the next element
Step 2:-search element 12 is compared with next element 20
A[6] = [65] [20] [10] [55] [32] [12]
A[0] A[1] A[2] A[3] A[4] A[5]
12
But are not matching so move to next element
Step 3:-searching element 12 is compared to the 10
A[6] = [65] [20] [10] [55] [32] [12]
A[0] A[1] A[2] A[3] A[4] A[5]
12
Both are not matching so move to the next element
Step 4:-search element 12 is compare with the next element 55
A[6] = [65] [20] [10] [55] [32] [12]
A[0] A[1] A[2] A[3] A[4] A[5]
12
Both are not matching so move to next element
Step 5:-search element 12 is compared with next element 32
A[6] = [65] [20] [10] [55] [32] [12]
A[0] A[1] A[2] A[3] A[4] A[5]
12
Both are not matching so move to next element
Step 6:-searching element is compared with next element 12
A[0] A[1] A[2] A[3] A[4] A[5]
12
Both matching are matching so we stop comparing and display element found at index 5
class linearsearch
{
public static void main(String[] args)
{
int i,n,item,flag=0;
Scanner ls = new Scanner(System.in);
System.out.println("Enter Size Of Array :");
n=ls.nextInt();
int[] a;//declaration of array
a=new int[n]; // Creation of array with given size
System.out.println("Enter unsorted Array :");
for(i=0;i<n;i++)
{
System.out.printf("\n Element a[%d] :",i);
a[i]=ls.nextInt();
}
System.out.print("\n Unsorted Array elements :");
for(i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
for(i=0;i<n;i++)
{
System.out.printf("\n ADDRESS=%h ---- ARRAY=a[%d]----- DATA=%d --- location=%d\n",i*4,i,a[i],i+1);
}
System.out.print("\n Enter the element to be searched :");
item=ls.nextInt();
for(i=0;i<n;i++)
{
if(a[i]==item)
{
System.out.printf("\n Element %d is found at location %d",item,i+1);
flag=1;
break;
}
}
if (flag==0)
System.out.printf("\n Element %d is not in the array",item);
}
}
No comments:
Post a Comment