Skip to content

Different way of implementing it, here is my contribution. #122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 21, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/Algorithms/Linear Search/Linear_Search.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Step-by-Step Explanation of Linear Search Code
*
* Definition:
* - It takes an array (arr) and a target value (target).
* - Loops through the array from index 0 to n-1.
* - If the current element matches target, it returns the index.
* - If no match is found after checking all elements, it returns -1 (meaning "not found").
*
* Inside the main method:
* - Defines an integer array {10, 20, 30, 40, 50}.
* - Calls search() with the array and the target (30).
* - If search() returns a valid index, it prints "Element found at index: X".
* - Otherwise, it prints "Element not found."
*
* How it executes:
* - It checks 10 → Not 30.
* - It checks 20 → Not 30.
* - It checks 30 → Match found at index 2 → Returns 2.
*
* Time Complexity:
* - Worst case: O(n) (If the target is at the end or not in the list).
* - Best case: O(1) (If the target is at position 0).

*/

// Linear Search method
public class LinearSearch{
public static int search(int[] arr, int target){
for (int i = 0; i < arr.length; i++){
if (arr[i] == target)
return i; // Return index if target is found
}
return -1; // Return -1 if target is not found
}

public static void main(String[] args){
// Example array
int[] numbers = {10, 20, 30, 40, 50};
int target = 30;

int result = search(numbers, target);
if (result != -1)
System.out.println("Element found at index: " + result);
else
System.out.println("Element not found.");
}
}