Search an element in an unsorted array using minimum number of comparisons
Last Updated :
29 Mar, 2024
Given an array of n distinct integers and an element x. Search the element x in the array using minimum number of comparisons. Any sort of comparison will contribute 1 to the count of comparisons. For example, the condition used to terminate a loop, will also contribute 1 to the count of comparisons each time it gets executed. Expressions like while (n) {n--;} also contribute to the count of comparisons as value of n is being compared internally so as to decide whether or not to terminate the loop.
Examples:
Input : arr[] = {4, 6, 1, 5, 8},
x = 1
Output : Found
Input : arr[] = {10, 3, 12, 7, 2, 11, 9},
x = 15
Output : Not Found
Asked in Adobe Interview
Below simple method to search requires 2n + 1 comparisons in worst case.
for (i = 0; i < n; i++) // Worst case n+1
if (arr[i] == x) // Worst case n
return i;
How to reduce number of comparisons?
The idea is to copy x (element to be searched) to last location so that one last comparison when x is not present in arr[] is saved.
Algorithm:
search(arr, n, x)
if arr[n-1] == x // 1 comparison
return "true"
backup = arr[n-1]
arr[n-1] = x
for i=0, i++ // no termination condition
if arr[i] == x // execute at most n times
// that is at-most n comparisons
arr[n-1] = backup
return (i < n-1) // 1 comparison
C++
// C++ implementation to search an element in
// the unsorted array using minimum number of
// comparisons
#include <bits/stdc++.h>
using namespace std;
// function to search an element in
// minimum number of comparisons
string search(int arr[], int n, int x)
{
// 1st comparison
if (arr[n - 1] == x)
return "Found";
int backup = arr[n - 1];
arr[n - 1] = x;
// no termination condition and thus
// no comparison
for (int i = 0;; i++) {
// this would be executed at-most n times
// and therefore at-most n comparisons
if (arr[i] == x) {
// replace arr[n-1] with its actual element
// as in original 'arr[]'
arr[n - 1] = backup;
// if 'x' is found before the '(n-1)th'
// index, then it is present in the array
// final comparison
if (i < n - 1)
return "Found";
// else not present in the array
return "Not Found";
}
}
}
// Driver program to test above
int main()
{
int arr[] = { 4, 6, 1, 5, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 1;
cout << search(arr, n, x);
return 0;
}
Java
// Java implementation to search an element in
// the unsorted array using minimum number of
// comparisons
import java.io.*;
class GFG {
// Function to search an element in
// minimum number of comparisons
static String search(int arr[], int n, int x)
{
// 1st comparison
if (arr[n - 1] == x)
return "Found";
int backup = arr[n - 1];
arr[n - 1] = x;
// no termination condition and thus
// no comparison
for (int i = 0;; i++) {
// this would be executed at-most n times
// and therefore at-most n comparisons
if (arr[i] == x) {
// replace arr[n-1] with its actual element
// as in original 'arr[]'
arr[n - 1] = backup;
// if 'x' is found before the '(n-1)th'
// index, then it is present in the array
// final comparison
if (i < n - 1)
return "Found";
// else not present in the array
return "Not Found";
}
}
}
// driver program
public static void main(String[] args)
{
int arr[] = { 4, 6, 1, 5, 8 };
int n = arr.length;
int x = 1;
System.out.println(search(arr, n, x));
}
}
// Contributed by Pramod Kumar
Python3
# Python3 implementation to search an
# element in the unsorted array using
# minimum number of comparisons
# function to search an element in
# minimum number of comparisons
def search(arr, n, x):
# 1st comparison
if (arr[n-1] == x) :
return "Found"
backup = arr[n-1]
arr[n-1] = x
# no termination condition and
# thus no comparison
i = 0
while(i < n) :
# this would be executed at-most n times
# and therefore at-most n comparisons
if (arr[i] == x) :
# replace arr[n-1] with its actual
# element as in original 'arr[]'
arr[n-1] = backup
# if 'x' is found before the '(n-1)th'
# index, then it is present in the
# array final comparison
if (i < n-1):
return "Found"
# else not present in the array
return "Not Found"
i = i + 1
# Driver Code
arr = [4, 6, 1, 5, 8]
n = len(arr)
x = 1
print (search(arr, n, x))
# This code is contributed by rishabh_jain
C#
// C# implementation to search an
// element in the unsorted array
// using minimum number of comparisons
using System;
class GFG {
// Function to search an element in
// minimum number of comparisons
static String search(int[] arr, int n, int x)
{
// 1st comparison
if (arr[n - 1] == x)
return "Found";
int backup = arr[n - 1];
arr[n - 1] = x;
// no termination condition and thus
// no comparison
for (int i = 0;; i++) {
// this would be executed at-most n times
// and therefore at-most n comparisons
if (arr[i] == x) {
// replace arr[n-1] with its actual element
// as in original 'arr[]'
arr[n - 1] = backup;
// if 'x' is found before the '(n-1)th'
// index, then it is present in the array
// final comparison
if (i < n - 1)
return "Found";
// else not present in the array
return "Not Found";
}
}
}
// driver program
public static void Main()
{
int[] arr = { 4, 6, 1, 5, 8 };
int n = arr.Length;
int x = 1;
Console.WriteLine(search(arr, n, x));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP implementation to
// search an element in
// the unsorted array
// using minimum number of
// comparisons
// function to search an
// element in minimum
// number of comparisons
function search($arr, $n, $x)
{
// 1st comparison
if ($arr[$n - 1] == $x)
return "Found";
$backup = $arr[$n - 1];
$arr[$n - 1] = $x;
// no termination
// condition and thus
// no comparison
for ($i = 0; ; $i++)
{
// this would be executed
// at-most n times and
// therefore at-most
// n comparisons
if ($arr[$i] == $x)
{
// replace arr[n-1]
// with its actual element
// as in original 'arr[]'
$arr[$n - 1] = $backup;
// if 'x' is found before
// the '(n-1)th' index,
// then it is present
// in the array
// final comparison
if ($i < $n - 1)
return "Found";
// else not present
// in the array
return "Not Found";
}
}
}
// Driver Code
$arr = array( 4, 6, 1, 5, 8 );
$n = sizeof($arr);
$x = 1;
echo(search($arr, $n, $x));
// This code is contributed by Ajit.
?>
JavaScript
<script>
// Javascript implementation to search an
// element in the unsorted array
// using minimum number of comparisons
// Function to search an element in
// minimum number of comparisons
function search(arr, n, x)
{
// 1st comparison
if (arr[n - 1] == x)
return "Found";
let backup = arr[n - 1];
arr[n - 1] = x;
// no termination condition and thus
// no comparison
for (let i = 0;; i++) {
// this would be executed at-most n times
// and therefore at-most n comparisons
if (arr[i] == x) {
// replace arr[n-1] with its actual element
// as in original 'arr[]'
arr[n - 1] = backup;
// if 'x' is found before the '(n-1)th'
// index, then it is present in the array
// final comparison
if (i < n - 1)
return "Found";
// else not present in the array
return "Not Found";
}
}
}
let arr = [ 4, 6, 1, 5, 8 ];
let n = arr.length;
let x = 1;
document.write(search(arr, n, x));
</script>
Output:
Found
Time Complexity: O(n)
Auxiliary Space: O(1)
Number of Comparisons: Atmost (n+2) comparisons
Similar Reads
Linear Search Algorithm Given an array, arr of n integers, and an integer element x, find whether element x is present in the array. Return the index of the first occurrence of x in the array, or -1 if it doesn't exist.Input: arr[] = [1, 2, 3, 4], x = 3Output: 2Explanation: There is one test case with array as [1, 2, 3 4]
9 min read
What is Linear Search? Linear search is defined as the searching algorithm where the list or data set is traversed from one end to find the desired value. Linear search method Linear search works by sequentially checking each element in the list until the desired value is found or the end of the list is reached. Propertie
3 min read
Linear Search in different languages
C Program for Linear SearchLinear Search is a sequential searching algorithm in C that is used to find an element in a list. Linear Search compares each element of the list with the key till the element is found or we reach the end of the list.ExampleInput: arr = {10, 50, 30, 70, 80, 60, 20, 90, 40}, key: 30Output: Key Found
4 min read
C++ Program For Linear SearchLinear search algorithm is the simplest searching algorithm that is used to find an element in the given collection. It simply compares the element to find with each element in the collection one by one till the matching element is found or there are no elements left to compare.In this article, we w
4 min read
Java Program for Linear SearchLinear Search is the simplest searching algorithm that checks each element sequentially until a match is found. It is good for unsorted arrays and small datasets.Given an array a[] of n elements, write a function to search for a given element x in a[] and return the index of the element where it is
2 min read
Linear Search - PythonGiven an array, arr of n elements, and an element x, find whether element x is present in the array. Return the index of the first occurrence of x in the array, or -1 if it doesnât exist.Examples:Input: arr[] = [10, 50, 30, 70, 80, 20, 90, 40], x = 30Output : 2Explanation: For array [10, 50, 30, 70,
4 min read
8085 program for Linear search | Set 2Problem - Write an assembly language program in 8085 microprocessor to find a given number in the list of 10 numbers, if found store 1 in output else store 0 in output. Example - Assumption - Data to be found at 2040H, list of numbers from 2050H to 2059H and output at 2060H. Algorithm - Load data by
2 min read
Recursive Linear Search Algorithm Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set.How Linear Search Works?Linear search works by comparing each element of the data s
6 min read
Sentinel Linear Search Sentinel Linear Search as the name suggests is a type of Linear Search where the number of comparisons is reduced as compared to a traditional linear search. In a traditional linear search, only N comparisons are made, and in a Sentinel Linear Search, the sentinel value is used to avoid any out-of-b
7 min read
Is Sentinel Linear Search better than normal Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case.The number of comparisons is reduced in this search as compared to a
8 min read
Improving Linear Search Technique A linear search or sequential search is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched. It is observed that when searching for a key element, then there is a possibility for searching the same
15+ min read
Linear search using Multi-threading Given a large file of integers, search for a particular element in it using multi-threading. Examples:Input : 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 20Key element foundInput :1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 202Key n
5 min read
Visualization of Linear Search
Some Problems on Linear Search
Number of comparisons in each direction for m queries in linear searchGiven an array containing N distinct elements. There are M queries, each containing an integer X and asking for the index of X in the array. For each query, the task is to perform linear search X from left to right and count the number of comparisons it took to find X and do the same thing right to
7 min read
Search an element in an unsorted array using minimum number of comparisonsGiven an array of n distinct integers and an element x. Search the element x in the array using minimum number of comparisons. Any sort of comparison will contribute 1 to the count of comparisons. For example, the condition used to terminate a loop, will also contribute 1 to the count of comparisons
7 min read
Search in a row wise and column wise sorted matrixGiven a matrix mat[][] and an integer x, the task is to check if x is present in mat[][] or not. Every row and column of the matrix is sorted in increasing order.Examples: Input: x = 62, mat[][] = [[3, 30, 38], [20, 52, 54], [35, 60, 69]]Output: falseExplanation: 62 is not present in the matrix.Inpu
14 min read