Java - Linear Search Example
Linear search, also called as sequential search, is a very simple method used for searching an array for a particular value. It works by comparing the value to be searched with every element of the array one by one in a sequence until a match is found. Linear search is mostly used to search an unordered list of elements (array in which data elements are not sorted).
For example, if an array A[] is declared and initialized as,
int A[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
and the value to be searched is VAL = 7, then searching means to find whether the value ‘7’ is present in the array or not.
If yes, then it returns the position of its occurrence.
Here,
POS = 3 (index starting from 0).
Algorithm for linear search:
LINEAR_SEARCH(A, N, VAL)
Step 1: [INITIALIZE] SET POS=-1
Step 2: [INITIALIZE] SETI=1
Step 3: Repeat Step 4 while I<=N
Step 4: IF A[I] = VAL
SET POS=I
PRINT POS
Go to Step 6
[END OF IF]
SET I=I+1
[END OF LOOP]
Step 5: IF POS = –1
PRINT VALUE IS NOT PRESENT
IN THE ARRAY
[END OF IF]
Step 6: EXIT
Example:
int arr[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
int search(int num, int arr[], int n) {
for(i=0;i<n;i++)
{
if(arr[i] == num)
{
return i;
}
}
return -1;
}
For example, if an array A[] is declared and initialized as,
int A[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
and the value to be searched is VAL = 7, then searching means to find whether the value ‘7’ is present in the array or not.
If yes, then it returns the position of its occurrence.
Here,
POS = 3 (index starting from 0).
Algorithm for linear search:
LINEAR_SEARCH(A, N, VAL)
Step 1: [INITIALIZE] SET POS=-1
Step 2: [INITIALIZE] SETI=1
Step 3: Repeat Step 4 while I<=N
Step 4: IF A[I] = VAL
SET POS=I
PRINT POS
Go to Step 6
[END OF IF]
SET I=I+1
[END OF LOOP]
Step 5: IF POS = –1
PRINT VALUE IS NOT PRESENT
IN THE ARRAY
[END OF IF]
Step 6: EXIT
Example:
int arr[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
int search(int num, int arr[], int n) {
for(i=0;i<n;i++)
{
if(arr[i] == num)
{
return i;
}
}
return -1;
}
Comments
Post a Comment