linear search algorithm code example

Example 1: linear search

#include <bits/stdc++.h>

using namespace std; 

int search(int arr[], int n, int key) 
{ 
    int i; 
    for (i = 0; i < n; i++) 
        if (arr[i] == key) 
            return i; 
    return -1; 
} 

int main() 
{ 
    int arr[] = { 99,4,3,8,1 }; 
    int key = 8; 
    int n = sizeof(arr) / sizeof(arr[0]); 

    int result = search(arr, n, key); 
    (result == -1) 
        ? cout << "Element is not present in array"
        : cout << "Element is present at index " << result; 

    return 0; 
}

Example 2: binary search algorithm

#include <bits/stdc++.h>

using namespace std;

int binarySearch(int arr[], int l, int h, int key){
    if(l<=h){
        int mid = l + (h-l)/2;

        if(arr[mid] == key){
            return mid;
        }

        else if(arr[mid] > key){
            return binarySearch(arr, l, mid-1, key);
        }

        else if(arr[mid] < key){
            return binarySearch(arr,mid+1, h, key);
        }
    }       

    return -1;
}

int main(){
    int arr[] = {1,2,3,4,5,6,7,8,9,10};
    int n = sizeof(arr)/sizeof(arr[0]);
    int key = 7;

    int result = binarySearch(arr,0,n-1,key);

    (result==-1)
        ? cout << "Element is not found in the array" << endl
        : cout << "Element is found at index " << result;

    return 0;

}

Example 3: 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 4: 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:

Cpp Example