In the realm of computer science and programming, searching is a fundamental operation. It involves finding a specific element within a collection of elements. One simple yet essential searching algorithm is the Linear Search.
What is Searching?
Searching is the process of finding a particular item in a collection of items. It is a common operation in many applications, ranging from databases to everyday programming tasks.
Linear Search
Linear Search is a straightforward searching algorithm that traverses a list sequentially to find a target element. It iterates through each element until a match is found or the entire list is searched. While not the most efficient algorithm for large datasets, it is easy to implement and applicable in various scenarios.
Linear Search Algorithm
Start at the beginning of the list.
Compare the target element with the current element.
If a match is found, return the index of the current element.
If the end of the list is reached without finding a match, return -1 to indicate that the element is not present.
Pseudocode
function linearSearch(array, target):
for each element in array:
if element equals target:
return index of element
return -1 // Element not found
Code for Linear Search
Let's delve into a basic implementation of Linear Search in Java:
publicclassLinearSearch {publicstaticintlinearSearch(int[] arr,int target) {for (int i =0; i <arr.length; i++) {if (arr[i] == target) {return i; // Element found, return its index } }return-1; // Element not found }publicstaticvoidmain(String[] args) {int[] array = {5,12,7,3,9,20};int targetElement =7;int result =linearSearch(array, targetElement);if (result !=-1) {System.out.println("Element found at index: "+ result); } else {System.out.println("Element not found in the array."); } }}
Time Complexity
The time complexity of the Linear Search algorithm is O(n), where 'n' is the number of elements in the list or array. It performs a constant amount of work for each element in the worst case.
🎯 Questions
Q1: Search in String
Write a Java function to perform a linear search for a specific character in a given string.
packageA06_searching.src;importjava.util.Objects;importjava.util.Scanner;publicclassLinear_search_strings {publicstaticvoidmain(String[] args) {Scanner in =newScanner(System.in);System.out.println("Enter the element you want to find: ");String[] array = {"ranit","manik","is","god"};String target =in.nextLine();// calling the function ==>System.out.println("The index of the searching element is: "+linear_search(array, target)); // index starts from '0' in the java }// searching in the array: return the index if found the item// otherwise if item not found return '-1'staticintlinear_search(String[] arr,String target) {if (arr.length==0) {return-1; }// run a for loop ==>for (int index =0; index <arr.length; index++) {// check for an element at every index if or is == target ==>String element = arr[index];if (Objects.equals(element, target)) {return index; } }// this line will execute ==> // if none of the above return statements have executed// ==> no return statement has been hit in the function// ==> hence the target is not foundreturn-1; // as '-1' cannot be an index value }}
Q2: Search in Range
Modify the linear search code to search for an element within a specified range in an array.
packageA06_searching.src;publicclasssearch_in_range {publicstaticvoidmain(String[] args) {int[] nums = {23,56,45,89,74,75,95,42,26,84,31,13};int target =89;// calling the function ==>System.out.println("The index of the searching element is: "+linear_search(nums, target,0,5)); // index starts from '0' in the java }// searching in the array: return the index if found the item// otherwise if item not found return '-1'staticintlinear_search(int[] arr,int target,int start,int end) {if (arr.length==0) {return-1; }// run a for loop ==>for (int index = start; index <= end; index++) {// check for an element at every index if or is == target ==>int element = arr[index];if (element == target) {return index; } }// this line will execute ==>// if none of the above return statements have executed// ==> no return statement has been hit in the function// ==> hence the target is not foundreturn-1; }}
Q3: Minimum Number
Implement a linear search to find the minimum number in an array.
packageA06_searching.src;importjava.util.Arrays;publicclassFind_minimum_number {publicstaticvoidmain(String[] args) {int[] arr = {12,51,65,654,32,547,98,15};System.out.println(Arrays.toString(arr));System.out.print("The minimum number is: "+min(arr)); }// assume arr.length != 0 ==>// return the minimum value in the array ==>staticintmin(int[] arr) {int min = arr[0]; // assuming the first element is the minimum numberfor (int j : arr) { // enhanced for loop which will 'min' the element if any element < minif (j < min) { min = j; } }return min; }}
Q4: Search in 2D Arrays
Extend the linear search algorithm to work with a two-dimensional array.
packageA06_searching.src;importjava.util.Arrays;importjava.util.Scanner;publicclassSearch_in_2D_array {publicstaticvoidmain(String[] args) {Scanner in =newScanner(System.in);// declaring and printing the array ==>int[][] arr = { {23,341,65}, {26,31}, {45,41,55,56}, {18,22} };for (int[] ints : arr) {System.out.println(Arrays.toString(ints)); }// taking input of the searching element ==>System.out.print("Enter the element you want to search: ");int target =in.nextInt();// printing the array with row and col no of search element ==>System.out.print("The following array contains row and column of the searching element: ");System.out.println(Arrays.toString(search(arr, target)));// format of return value (array) ==> {row, col} }staticint[] search(int[][] array,int target) {for (int row =0; row <array.length; row++) {for (int col =0; col < array[row].length; col++) {if (array[row][col] == target) {returnnewint[]{row, col}; // creating and returning a new array which contains ==> // {row, col} elements } } }/* this is enhanced for loop you can go with ==> for (int[] ints : array) { for (int anInt : ints) { if (anInt == target) { return 1; } } } */returnnewint[]{-1,-1}; }}
packageA06_searching.src;publicclassMaxWealth {publicstaticvoidmain(String[] args) { }publicintmaximumWealth(int[][] accounts) {// person = rol// account = colint ans =Integer.MIN_VALUE;for (int[] ints : accounts) {// when you start a new row, take a new sum for that rowint sum =0;for (int anInt : ints) { sum += anInt; }// now we have sum of accounts of person// check with overall ansif (sum > ans) { ans = sum; } }return ans; }}
Feel free to explore and experiment with these questions to deepen your understanding of linear search in Java. Happy coding!