linear search functin code example

Example 1: linear search

def global_linear_search(target, array)
  counter = 0
  results = []

  while counter < array.length
    if array[counter] == target
      results << counter
      counter += 1
    else
      counter += 1
    end
  end

  if results.empty?
    return nil
  else
    return results
  end
end

Example 2: linear search

//Java implementation of Linear Search

import java.util.Scanner;

public class LinearSearch {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int[] a = {10,20,50,30,40};
		int key=sc.nextInt(),flag=0;
		
		for(int i=0;i<a.length;i++)	
		{
			if(a[i]==key)
			{
				flag=1;
				break;
			}
			else
			{
				flag=0;
			}
		}
		if(flag==1)
		{
			System.out.println("Success! Key ("+ key + ") found");
		}
		else
		{
			System.out.println("Error! This key (" + key + ") does not exist in the array");
		}
	}

}

Tags:

Java Example