Last active
March 3, 2022 10:38
-
-
Save bikashdaga/c79596b2d158594192eb6f14771db362 to your computer and use it in GitHub Desktop.
Linear Search Algorithm in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Input: | |
public class ScalerTopics | |
{ | |
public static void main(String[] args) { | |
int[] array = new int[] {5, 3, 12, 9, 45, 1, 22}; | |
int K = 9; | |
int result = linearSearch(array, K); | |
if (result >= 0) { | |
System.out.println(K + " found at index: " + result); | |
} else { | |
System.out.println(K + " not found"); | |
} | |
} | |
private static int linearSearch(int[] array, int K) { | |
int n = array.length; | |
for (int index = 0; index < n; ++index) { | |
if (array[index] == K) { | |
return index; | |
} | |
} | |
return -1; | |
} | |
} | |
Output: | |
9 found at index: 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Linear search is a process of searching elements from the unordered set of groups. Since the data is unordered, we don't have other options other than searching elements one by one sequentially. It is also called the sequential search.
To know more about Linear Search read this article on Scaler Topics.
Happy Learning!