Linear Search

Linear Search

Today was an exciting day as I delved into the world of algorithms and data structures. I decided to start with a fundamental search algorithm called "Linear Search" in Java. This algorithm is straightforward but essential to understand the principles of searching within arrays.

What is Linear Search?
Linear search, also known as sequential search, is a simple searching algorithm that iterates through an array to find the target element. It checks each element one by one until the desired element is found, or the entire array has been traversed.

Implementation:
In Java, I implemented the linear search algorithm using a method that takes an array and the target element as input. The method returns the index of the target element if found or -1 if the element does not exist in the array.

Here's the code I wrote:
public class Linear{
static int search(int arr[], key){
for(int i=0; i<arr.length; i++)
if(arr[i]==key){
return 1;
}
return -1;

public static void main(String[] args){
int arr[] = {2,4,6,8,10,12,14};
int key = 12;

int index = search(arr,key);
if(index== -1){
System.out.println("Key not found");
}
else{
System.out.print("Key found in the array: " + index);
}
}

#datastructuresandalgorithms #dsacoding #dsacoding #code #consistencymatters #consistencyiskey #newbeginnings #start #developers #developercommunity