Searching Algorithms
Learn how to perform a linear and binary search in Java.
We'll cover the following...
Overview
One of the main advantages a computer offers is storing large amounts of data. Computers can find things quicker than humans. This capability is called searching. There are two main types of searching techniques:
- Sequential search
- Binary search
Sequential search
Going through all items, one by one, until we find the desired item is called a sequential search. It is also known as a linear search.
For example, if we have the following array, and we need to find , we’ll check all the elements one by one.
It’s very easy to code a sequential search in Java. Let’s begin.
class SequentialSearch{public static int search(int[] array, int value){for(int i = 0; i < array.length; i++) // Traversing through array{if(value == array[i]) // If element foundreturn i;}return -1; // Element not found}public static void main( String args[] ) {int[] array = {1, -2, 71, -4, 40, 32};// Searching different valuesSystem.out.println(search(array, -4));System.out.println(search(array, 0));}}
Look at line 3. We create the header of the search()
function. It takes the array and a value that is to be searched. As a result, it will return the index of the value. If the value isn’t found, it returns ...