Searching Algorithms

This lesson discusses how linear search works and explains the implementation of binary search in detail.

Brute force: Linear search

This is the most simple searching algorithm, and it is in O(n)O(n) time. In fact, give it a shot. You’ll probably be able to come up with it yourself!

Press + to interact
main.java
Helper.java
class Search {
public static int linearSearch(int s, int[] arr, int arrSize) {
// Write your code here
return Integer.MAX_VALUE;
}
}

How linear search works

Go through each element one by one. When the element that you are searching for is found, return its index. Here are some slides to make things clearer:

...
Press + to interact
main.java
Helper.java
class Search {
public static int linearSearch(int s, int[] arr, int arrSize) {
if (arrSize <= 0) // Sanity check
return -1;
for (int i = 0; i < arrSize; i++)
if (arr[i] == s)
return i; // If found return index
return -1; // Return -1 otherwise
}
public static void main(String args[]) {
int arr[] = {5,4,1,410,5,95,4,-100,20,0};
int arrSize = 10;
int key = 0;
Helper obj = new Helper();
System.out.println("Given Array");
obj.printArray(arr, arrSize);
int index = linearSearch(key, arr, arrSize);
if (index != -1)
System.out.println("Your key \"" + key + "\" is found at index \"" + index + "\"");
else
System.out.println(key + " not found in the array: ");
}
}
...
Access this course and 1400+ top-rated courses and projects.