Introduction
Linear Search Algorithm: Start searching the element from the first element till you get the element you are looking for.
Time Complexity :
- Best case: Element is found in the first place.
- Worst case: Element is not found at all(loop has to iterate over all the elements of an array)
Code for Linear Search
//linear search for an array by geeting indexvalue of target
static int lsearch(int[] arr,int target){
if(arr.length==0){
return -1;
}
//run a loop
for (int index = 0; index < arr.length ; index++) {
if(arr[index]==target){
return index;
}
}
//if none of the above conditions are true
return -1;
}
}
Linear search in the range code
//linear search for an array by getting indexvalue of target in the given range
static int lsearch(int[] arr,int target , int start , int end){
//start and end are range of index in which element is need to be found
if(arr.length==0){
return -1;
}
//run a loop
for (int index = start; index < end ; index++) {
if(arr[index]==target){
return index;
}
}
//if none of the above conditions are true
return -1;
}
Code for Max and Min Value
//find maximum number in an array
static int maxValue(int[] arr){
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if(arr[i]>max){
max = arr[i];
}
}
return max;
}
//find minimum number in an array
static int minValue(int[] arr){
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if(arr[i]<min){
min = arr[i];
}
}
return min;
}
Linear search in 2D Array
//linear search in an 2D Array
//return format {row,col} of element of the index to be found
static int[] lsearch2d(int[][] arr,int target){
for (int row = 0; row < arr.length; row++) {
for (int column = 0; column <arr[row].length ; column++) {
if(arr[row][column]==target){
return new int[]{row,column};
}
}
}
return new int[]{-1,-1};
}