Linear Search Algorithm variations in Java

Linear Search is a brute force approach or sequential approach for finding value in a list of values. Even though, it is a single algorithm, can be written in many ways to simplify algorithmic time complexity based on input values. Linear Search can be a Brute force solution, it’s worst cost is proportional to the number of elements in the list. Linear search with sorted array as an input, we can improve the complexity by checking condition that the element is more than that it is being compared with, we can just ignore searching in the later part of the array. Some times Recursion is easy to code, Linear search can be written in a recursive fashion.

Here is the implementation for Linear Search Algorithm variations in Java

1.Linear Search (Bruteforce)

/**<p>Finding an element through linear search --BruteForce method</p>
	 * @param a
	 * @param number
	 * @return searchIndex
	 * Time Complexity :
	 * Best case  : O(1)
	 * Worst case : O(n)
	 */
public static int linearSearch(int[] a,int number){
//length of the array
int n=a.length;
//Bruteforce method :: loop through n numbers if element found return the index, else return -1
for(int i=0;i<n;i++){
  if(a[i]==number){
    return i;
  }
}
return -1;		
}

2.Linear Search with Recursion

/**
	 * <p>Recursive solution for Linear Search</p>
	 * @param keys
	 * @param key
	 * @param low
	 * @param high
	 * @return
	 */
public static int linearSearchWithRecursion( int[] keys, int key, int low, int high ) {
if (low > high) {
// There are no more keys left.
return -1;
} else if (keys[ low ] != key) {
// Search for key in remaining keys.
return linearSearchWithRecursion( keys, key, low + 1, high );
} else {
// We’ve located key.
return low;
 }
}

A sample Test client for above two algorithms

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr={1,4,5,3,2,0,8,6};
int searchIndex=linearSearch(arr,0);

if(searchIndex==-1)
   System.out.println("Element you are searching for is not found!");
else
   System.out.println("Element at an Index position "+searchIndex);

 int recursiveIndex=linearSearchWithRecursion(arr,0,0,arr.length-1);

if(recursiveIndex==-1)
   System.out.println("Element you are searching for is not found!");
else
   System.out.println("Element at an Index position "+recursiveIndex);

}

3.Sorted Array Linear Search

package com.jminded.algorithms.search;

public class SortedArrayLinearSearch {

	/**
	 * @author Umashankar
	 * {@link https://jminded.com}
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr={0,1,2,4,5,6,7};
		int searchIndex=linearSearch(arr,3);
		System.out.println("Element at search index "+searchIndex);
        searchIndex=linearSearch(arr, 7);
        System.out.println("Element at search index "+searchIndex);
	}
	/**
	 * <p>UnSorted Array LinearSearch</p>
	 * @param a
	 * @param number
	 * @return
	 * Time Complexity ::  O(n) 
	 * Space Complexity :: O(1)
	 */
	public static int linearSearch(int[] a,int number){
		int n=a.length;
		for(int i=0;i<n;i++){
			if(a[i]==number)
				return i;
			/*As it is sorted array, no need to search for element after 
			crossing the array number greater than the number we want to search.*/
			else if(a[i]>number) 
				return -1;
		}
		return -1;
	}

}

0 thoughts on “Linear Search Algorithm variations in Java”

  1. do you make all these normal professional problems

    also there is one very easy to use indisputable fact that you can instigate and make serious money while using it. the is very easy, “exclusively conform with, emulate the actions in the bold, And you’ll be making a lot of cash. for example, If you wanted to go to a city, But you do not know which one way to take. precisely what every day do is considered wonder someone that have been there long before. so why,the actual? considering that they are there and they recognize how to get there! it’s the point. Below latamdate.com reviews are some of the common goof ups your acquaintances quite often probably did. The lavish ran into decided regarding these issues and they’ve learned from it. Now it is important to learn off their flaws, not to make items when. carry out an individuals footsteps, and you will be full.1. buying a long time just learning also analyzing your small business. wedding and reception do the following. actually that learn invariably, But with regards to action is to win gigantic attack! always remember this, it might be act which will provide satisfaction, must not hanging out practicing. awareness is certainly dominant, ONLY once you discover to sprinkle! realizing is simply always experiences buy mentally if you don’t know how to use it. so that, endure n enormous decisions on your website.2. to make serious blunder written by convinced that web is as common as supping water. thus, this will be a wrong concept that a lot see. ever I professionally made this error. Just which have could possibly have look for posters nevertheless web in your own home, easily and you could make lots of cash by it? Yes you can generate large income also it can be instant. however this is only if you spend your energy lighting up extremely! do not miscalculate internet my good friend. Every small business time to set, And you have got to put a ton of labour in the container. consider this, there is not really extra cash on earth. take a look at earn more money for the internet, Then you should pay for the fee, determination.3. turning to another location net service provider too fast. precisely what is happening to alot of people. later, assuming that internet affiliate are you still come across little or no improvements, they’re a choice between stop trying as switch to the next associate little. guess what happens, it is just a business, And you desire to make walk away income from using it. you will need to generate an income may possibly dominate manufactured job. So a person have to on the least bring a regarding it to set! it is not easy to manufacture another re-occurring income your net, question you’ve decided to bring in more cash for the web, however barely stick to your web marketing insurance company, and hang some work in the gift basket. 4. consider to join a joint venture partner agency pretty quickly variation. what i’m saying totally free that people join the opportunity an affiliate network if you don’t take adequate examine within. this runs specifically true for neophytes who want to earn more money on the. cause are you aware I let them know? merely new comers almost never come across with landing page, web page landing page of an affiliate program. they will certainly then really easily manipulate according to all the easy worthwhile methods, on top of that work with these kinds of not including whole lot accounts. you might want to incredibly least be diligent which affiliate program that you pick out in the past registering with this kind of.5. Fail for you to trace outcomes of promotional tool, uncover throwing hard work. This is a second malfunction that every internet marketers conducted. some people i never thought of how for you to trace specific numbers, ask yourself how member and even internet site visitors pertains to the website. You should keep an eye as part of your web page not to mention individual statistics reveal make a lot more sales actions. why should you? as this is where your wages steady stream manufactured. these are generally the actual as well as guide at the moment.

    Reply

Leave a Comment