Skip to content

Instantly share code, notes, and snippets.

@bikashdaga
Last active March 3, 2022 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bikashdaga/c79596b2d158594192eb6f14771db362 to your computer and use it in GitHub Desktop.
Save bikashdaga/c79596b2d158594192eb6f14771db362 to your computer and use it in GitHub Desktop.
Linear Search Algorithm in Java
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
@bikashdaga
Copy link
Author

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment