In this post, we will look into search operation in an Array, i.e., how to search an element in an Array, such as:
- Searching in an Unsorted Array using Linear Search
- Searching in a Sorted Array using Linear Search
- Searching in a Sorted Array using Binary Search
Searching operations in an Unsorted Array using Linear Search
In an unsorted array, the search operation can be performed by linear traversal from the first element to the last element, i.e. Linear Search
Coding implementation of the search operation:
C++
// C++ program to implement linear // search in unsorted array #include <bits/stdc++.h> using namespace std; Â
// Function to implement search operation int findElement( int arr[], int n, int key) { Â Â Â Â int i; Â Â Â Â for (i = 0; i < n; i++) Â Â Â Â Â Â Â Â if (arr[i] == key) Â Â Â Â Â Â Â Â Â Â Â Â return i; Â
    // If the key is not found     return -1; } Â
// Driver's Code int main() { Â Â Â Â int arr[] = { 12, 34, 10, 6, 40 }; Â Â Â Â int n = sizeof (arr) / sizeof (arr[0]); Â
    // Using a last element as search element     int key = 40; Â
    // Function call     int position = findElement(arr, n, key); Â
    if (position == -1)         cout << "Element not found" ;     else         cout << "Element Found at Position: "              << position + 1; Â
    return 0; } Â
// This code is contributed // by Akanksha Rai |
C
// C program to implement linear // search in unsorted array #include <stdio.h> Â
// Function to implement search operation int findElement( int arr[], int n, int key) { Â Â Â Â int i; Â Â Â Â for (i = 0; i < n; i++) Â Â Â Â Â Â Â Â if (arr[i] == key) Â Â Â Â Â Â Â Â Â Â Â Â return i; Â
    // If the key is not found     return -1; } Â
// Driver's Code int main() { Â Â Â Â int arr[] = { 12, 34, 10, 6, 40 }; Â Â Â Â int n = sizeof (arr) / sizeof (arr[0]); Â
    // Using a last element as search element     int key = 40; Â
    // Function call     int position = findElement(arr, n, key); Â
    if (position == -1)         printf ( "Element not found" );     else         printf ( "Element Found at Position: %d" ,                position + 1); Â
    return 0; } |
Java
// Java program to implement linear // search in unsorted arrays Â
class Main { Â
    // Function to implement     // search operation     static int findElement( int arr[], int n, int key)     {         for ( int i = 0 ; i < n; i++)             if (arr[i] == key)                 return i; Â
        // If the key is not found         return - 1 ;     } Â
    // Driver's Code     public static void main(String args[])     {         int arr[] = { 12 , 34 , 10 , 6 , 40 };         int n = arr.length; Â
        // Using a last element as search element         int key = 40 ; Â
        // Function call         int position = findElement(arr, n, key); Â
        if (position == - 1 )             System.out.println( "Element not found" );         else             System.out.println( "Element Found at Position: "                                + (position + 1 ));     } } |
Python3
# Python program for searching in # unsorted array Â
Â
def findElement(arr, n, key): Â Â Â Â for i in range (n): Â Â Â Â Â Â Â Â if (arr[i] = = key): Â Â Â Â Â Â Â Â Â Â Â Â return i Â
    # If the key is not found     return - 1 Â
Â
# Driver's code if __name__ = = '__main__' : Â Â Â Â arr = [ 12 , 34 , 10 , 6 , 40 ] Â Â Â Â key = 40 Â Â Â Â n = len (arr) Â
    # search operation     index = findElement(arr, n, key)     if index ! = - 1 :         print ( "Element Found at position: " + str (index + 1 ))     else :         print ( "Element not found" ) Â
    # Thanks to Aditi Sharma for contributing     # this code |
C#
// C# program to implement linear // search in unsorted arrays using System; Â
class main {     // Function to implement     // search operation     static int findElement( int [] arr, int n, int key)     {         for ( int i = 0; i < n; i++)             if (arr[i] == key)                 return i; Â
        // If the key is not found         return -1;     } Â
    // Driver Code     public static void Main()     {         int [] arr = { 12, 34, 10, 6, 40 };         int n = arr.Length; Â
        // Using a last element as         // search element         int key = 40;         int position = findElement(arr, n, key); Â
        if (position == -1)             Console.WriteLine( "Element not found" );         else             Console.WriteLine( "Element Found at Position: "                               + (position + 1));     } } Â
//Â This code is contributed by vt_m. |
Javascript
// Javascript program to implement linear // search in unsorted array Â
Â
// Function to implement search operation function findElement( arr, n, key) { Â Â Â Â let i; Â Â Â Â for (i = 0; i < n; i++) Â Â Â Â Â Â Â Â if (arr[i] == key) Â Â Â Â Â Â Â Â Â Â Â Â return i; Â
    return -1; } Â
Â
         // Driver program          let arr = [12, 34, 10, 6, 40];     let n = arr.length; Â
    // Using a last element as search element     let key = 40;     let position = findElement(arr, n, key); Â
    if (position == - 1)         document.write( "Element not found" );     else         document.write( "Element Found at Position: "              + (position + 1)); |
PHP
<?php // PHP program to implement linear // search in unsorted array Â
// Function to implement // search operation function findElement( $arr , $n , $key ) {     $i ;     for ( $i = 0; $i < $n ; $i ++)         if ( $arr [ $i ] == $key )             return $i ;            // If the key is not found     return -1; } Â
// Driver Code $arr = array (12, 34, 10, 6, 40); $n = sizeof( $arr ); Â
// Using a last element // as search element $key = 40; $position = findElement( $arr , $n , $key ); Â
if ( $position == - 1)     echo ( "Element not found" ); else     echo ( "Element Found at Position: " . ( $position + 1)); Â
// This code is contributed by Ajit. ?> |
Element Found at Position: 5
Time Complexity: O(N)Â
Auxiliary Space: O(1)
Searching in a Sorted Array using Linear Search
In a sorted array, the most trivial method for search operation is by using Linear Search.
Below is the implementation of the above approach:
C++
// C++ program to implement linear // search in sorted array #include <bits/stdc++.h> using namespace std; Â
// Function to implement search operation int findElement( int arr[], int n, int key) { Â Â Â Â int i; Â Â Â Â for (i = 0; i < n; i++) Â Â Â Â Â Â Â Â if (arr[i] == key) Â Â Â Â Â Â Â Â Â Â Â Â return i; Â
    // If the key is not found     return -1; } Â
// Driver's Code int main() { Â Â Â Â int arr[] = { 5, 6, 7, 8, 9, 10 }; Â Â Â Â int n = sizeof (arr) / sizeof (arr[0]); Â
    // Using a last element as search element     int key = 10; Â
    // Function call     int position = findElement(arr, n, key); Â
    if (position == -1)         cout << "Element not found" ;     else         cout << "Element Found at Position: "              << position + 1; Â
    return 0; } Â
// This code is contributed // by Akanksha Rai |
C
// C program to implement linear // search in sorted array #include <stdio.h> Â
// Function to implement search operation int findElement( int arr[], int n, int key) { Â Â Â Â int i; Â Â Â Â for (i = 0; i < n; i++) Â Â Â Â Â Â Â Â if (arr[i] == key) Â Â Â Â Â Â Â Â Â Â Â Â return i; Â
    // If the key is not found     return -1; } Â
// Driver's Code int main() { Â Â Â Â int arr[] = { 5, 6, 7, 8, 9, 10 }; Â Â Â Â int n = sizeof (arr) / sizeof (arr[0]); Â
    // Using a last element as search element     int key = 10; Â
    // Function call     int position = findElement(arr, n, key); Â
    if (position == -1)         printf ( "Element not found" );     else         printf ( "Element Found at Position: %d" ,                position + 1); Â
    return 0; } |
Java
// Java program to implement linear // search in sorted arrays Â
class Main { Â
    // Function to implement     // search operation     static int findElement( int arr[], int n, int key)     {         for ( int i = 0 ; i < n; i++)             if (arr[i] == key)                 return i; Â
        // If the key is not found         return - 1 ;     } Â
    // Driver's Code     public static void main(String args[])     {         int arr[] = { 5 , 6 , 7 , 8 , 9 , 10 };         int n = arr.length; Â
        // Using a last element as search element         int key = 10 ; Â
        // Function call         int position = findElement(arr, n, key); Â
        if (position == - 1 )             System.out.println( "Element not found" );         else             System.out.println( "Element Found at Position: "                                + (position + 1 ));     } } |
Python3
# Python program for searching in # sorted array Â
Â
def findElement(arr, n, key): Â Â Â Â for i in range (n): Â Â Â Â Â Â Â Â if (arr[i] = = key): Â Â Â Â Â Â Â Â Â Â Â Â return i Â
    # If the key is not found     return - 1 Â
Â
# Driver's code if __name__ = = '__main__' : Â Â Â Â arr = [ 5 , 6 , 7 , 8 , 9 , 10 ] Â Â Â Â key = 10 Â Â Â Â n = len (arr) Â
    # search operation     index = findElement(arr, n, key)     if index ! = - 1 :         print ( "Element Found at position: " + str (index + 1 ))     else :         print ( "Element not found" ) Â
    # Thanks to Aditi Sharma for contributing     # this code |
C#
// C# program to implement linear // search in sorted arrays using System; Â
class main {     // Function to implement     // search operation     static int findElement( int [] arr, int n, int key)     {         for ( int i = 0; i < n; i++)             if (arr[i] == key)                 return i; Â
        // If the key is not found         return -1;     } Â
    // Driver Code     public static void Main()     {         int [] arr = { 5, 6, 7, 8, 9, 10 };         int n = arr.Length; Â
        // Using a last element as         // search element         int key = 10;         int position = findElement(arr, n, key); Â
        if (position == -1)             Console.WriteLine( "Element not found" );         else             Console.WriteLine( "Element Found at Position: "                               + (position + 1));     } } Â
//Â This code is contributed by vt_m. |
Javascript
// Javascript program to implement linear // search in sorted array Â
Â
// Function to implement search operation function findElement( arr, n, key) { Â Â Â Â let i; Â Â Â Â for (i = 0; i < n; i++) Â Â Â Â Â Â Â Â if (arr[i] == key) Â Â Â Â Â Â Â Â Â Â Â Â return i; Â
    return -1; } Â
Â
         // Driver program          let arr = [5, 6, 7, 8, 9, 10];     let n = arr.length; Â
    // Using a last element as search element     let key = 10;     let position = findElement(arr, n, key); Â
    if (position == - 1)         document.write( "Element not found" );     else         document.write( "Element Found at Position: "              + (position + 1)); |
PHP
<?php // PHP program to implement linear // search in sorted array Â
// Function to implement // search operation function findElement( $arr , $n , $key ) {     $i ;     for ( $i = 0; $i < $n ; $i ++)         if ( $arr [ $i ] == $key )             return $i ;            // If the key is not found     return -1; } Â
// Driver Code $arr = array (5, 6, 7, 8, 9, 10); $n = sizeof( $arr ); Â
// Using a last element // as search element $key = 10; $position = findElement( $arr , $n , $key ); Â
if ( $position == - 1)     echo ( "Element not found" ); else     echo ( "Element Found at Position: " . ( $position + 1)); Â
// This code is contributed by Ajit. ?> |
Element Found at Position: 6
Time Complexity: O(N)Â
Auxiliary Space: O(1)
Searching in a Sorted Array using Binary Search
In a sorted array, the search operation can be performed efficiently by using binary search.
Below is the implementation of the above approach:
C++
// C++ program to implement binary search in sorted array #include <bits/stdc++.h> using namespace std; Â
int binarySearch( int arr[], int low, int high, int key) { Â Â Â Â if (high < low) Â Â Â Â Â Â Â Â return -1; Â Â Â Â int mid = (low + high) / 2; /*low + (high - low)/2;*/ Â Â Â Â if (key == arr[mid]) Â Â Â Â Â Â Â Â return mid; Â Â Â Â if (key > arr[mid]) Â Â Â Â Â Â Â Â return binarySearch(arr, (mid + 1), high, key); Â Â Â Â return binarySearch(arr, low, (mid - 1), key); } Â
/* Driver code */ int main() {     // Let us search 3 in below array     int arr[] = { 5, 6, 7, 8, 9, 10 };     int n, key; Â
    n = sizeof (arr) / sizeof (arr[0]);     key = 10; Â
    // Function call     cout << "Index: " << binarySearch(arr, 0, n - 1, key)          << endl;     return 0; } Â
// This code is contributed by NamrataSrivastava1 |
C
// C program to implement binary search in sorted array #include <stdio.h> Â
int binarySearch( int arr[], int low, int high, int key) { Â Â Â Â if (high < low) Â Â Â Â Â Â Â Â return -1; Â Â Â Â int mid = (low + high) / 2; /*low + (high - low)/2;*/ Â Â Â Â if (key == arr[mid]) Â Â Â Â Â Â Â Â return mid; Â Â Â Â if (key > arr[mid]) Â Â Â Â Â Â Â Â return binarySearch(arr, (mid + 1), high, key); Â Â Â Â return binarySearch(arr, low, (mid - 1), key); } Â
/* Driver Code */ int main() {     // Let us search 3 in below array     int arr[] = { 5, 6, 7, 8, 9, 10 };     int n, key; Â
    n = sizeof (arr) / sizeof (arr[0]);     key = 10; Â
    // Function call     printf ( "Index: %d\n" , binarySearch(arr, 0, n - 1, key));     return 0; } |
Java
// Java program to implement binary // search in a sorted array Â
class Main {     // function to implement     // binary search     static int binarySearch( int arr[], int low, int high,                             int key)     {         if (high < low)             return - 1 ; Â
        /*low + (high - low)/2;*/         int mid = (low + high) / 2 ;         if (key == arr[mid])             return mid;         if (key > arr[mid])             return binarySearch(arr, (mid + 1 ), high, key);         return binarySearch(arr, low, (mid - 1 ), key);     } Â
    /* Driver Code*/     public static void main(String[] args)     {         int arr[] = { 5 , 6 , 7 , 8 , 9 , 10 };         int n, key;         n = arr.length - 1 ;         key = 10 ; Â
        // Function call         System.out.println( "Index: "                            + binarySearch(arr, 0 , n, key));     } } |
Python3
# python 3Â program to implement # binary search in sorted array Â
Â
def binarySearch(arr, low, high, key): Â
    mid = (low + high) / 2 Â
    if (key = = arr[ int (mid)]):         return mid Â
    if (key > arr[ int (mid)]):         return binarySearch(arr,                             (mid + 1 ), high, key) Â
    if (key < arr[ int (mid)]):         return binarySearch(arr, low, (mid - 1 ), key) Â
    return 0 Â
Â
# Driver code if __name__ = = "__main__" :     # Let us search 3 in below array     arr = [ 5 , 6 , 7 , 8 , 9 , 10 ]     n = len (arr)     key = 10 Â
    # Function call     print ( "Index:" , int (binarySearch(arr, 0 , n - 1 , key))) Â
# This code is contributed by # Smitha Dinesh Semwal |
C#
// C# program to implement binary // search in a sorted array Â
using System; Â
public class GFG { Â
    // function to implement     // binary search     public static int binarySearch( int [] arr, int low,                                    int high, int key)     {         if (high < low) {             return -1;         } Â
        int mid = (low + high) / 2;         if (key == arr[mid]) {             return mid;         }         if (key > arr[mid]) {             return binarySearch(arr, (mid + 1), high, key);         }         return binarySearch(arr, low, (mid - 1), key);     } Â
    /* Driver Code */     public static void Main( string [] args)     {         int [] arr = new int [] { 5, 6, 7, 8, 9, 10 };         int n, key;         n = arr.Length;         key = 10; Â
        // Function call         Console.WriteLine(             "Index: " + binarySearch(arr, 0, n - 1, key));     } } Â
// This code is contributed by Shrikant13 |
Javascript
<script> Â
Â
// Javascript program to implement // binary search in sorted array Â
function binarySearch( arr, low, high, key) { Â Â Â Â if (high < low) Â Â Â Â Â Â Â Â return -1; Â Â Â Â Â Â Â Â /*low + (high - low)/2;*/ Â Â Â Â let mid = Math.trunc((low + high) / 2); Â Â Â Â if (key == arr[mid]) Â Â Â Â Â Â Â Â return mid; Â Â Â Â if (key > arr[mid]) Â Â Â Â Â Â Â Â return binarySearch(arr, (mid + 1), high, key); Â Â Â Â return binarySearch(arr, low, (mid - 1), key); } Â
         // Driver program          // Let us search 3 in below array     let arr = [ 5, 6, 7, 8, 9, 10 ];     let n, key; Â
    n = arr.length;     key = 10; Â
    document.write( "Index: " + binarySearch(arr, 0, n - 1, key)     + "</br>" );           </script> |
PHP
<?php // PHP program to implement // binary search in sorted array Â
function binarySearch( $arr , $low , Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â $high , $key ) { Â Â Â Â if ( $high < $low ) Â Â Â Â return -1; Â Â Â Â Â Â Â Â Â $mid = (int)( $low + $high ) / 2; Â Â Â Â Â Â Â Â Â if ( $key == $arr [(int) $mid ]) Â Â Â Â Â Â Â Â return $mid ; Â Â Â Â Â Â Â Â Â if ( $key > $arr [(int) $mid ]) Â Â Â Â Â Â Â Â return binarySearch( $arr , ( $mid + 1), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â $high , $key ); Â Â Â Â Â Â Â Â Â return (binarySearch( $arr , $low , Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ( $mid -1), $key )); } Â
// Driver Code Â
// Let us search 3 in below array $arr = array (5, 6, 7, 8, 9, 10); $n = count ( $arr ); $key = 10; Â
// Function call echo "Index: " , (int)binarySearch( $arr , 0, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â $n -1, $key ); Â
// This code is contributed by // Srathore ?> |
Index: 5
Time Complexity: O(log(n)) Using Binary Search
Auxiliary Space: O(log(n)) due to recursive calls, otherwise iterative version uses Auxiliary Space of O(1).
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!