Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Can Binary Search be applied in an Unsorted Array

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is stored. Mainly the widely used searching algorithms are:

Linear Search: In this, the list or array is traversed sequentially and every element is checked. And linear search can be implemented on both sorted and unsorted arrays or lists. The linear search has a linear time complexity i.e. O(N) 

Binary Search: It is a searching algorithm which is specifically designed for searching in sorted data structures. This searching algorithm is much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half. It has logarithmic time complexity i.e. O(log N).

Now, the question arises, is Binary Search applicable on unsorted arrays?

So, the answer is NO, it is not possible to use or implement Binary Search on unsorted arrays or lists, because, the repeated targeting of the mid element of one half depends on the sorted order of data structure.

Workaround to apply binary search in an unsorted array:

However, if there is a need to do so explicitly then:

Construct an auxiliary array of pairs of elements with their indices and simply sort the array and perform binary search for given X on sorted auxiliary array

Follow the below steps:

  • For every element in array write elements and their indices in an auxiliary array of pairs.
  • Sort auxiliary array.
  • For the given value X perform Binary Search on the sorted auxiliary array,  
    • Let position be the index where element X is in auxiliary array.
  • Return index of element in original array arr(aux_array[position].second).

Below is the implementation of the above approach: 

C++




// C++ program for the above approach:
 
#include <bits/stdc++.h>
using namespace std;
 
vector<pair<int, int> > aux_arr;
 
// Function to make auxiliary array
void make_aux_array(int arr[], int n)
{
    aux_arr.resize(n);
 
    // For every element in array write
    // elements and their indices in
    // auxiliary array of pairs.
    for (int i = 0; i < n; i++) {
        aux_arr[i] = { arr[i], i };
    }
 
    // Sort auxiliary array.
    sort(aux_arr.begin(), aux_arr.end());
}
 
// Function to perform binary search
int binarySearch(int arr[], int n, int x)
{
    // For given value x perform
    // Binary Search on sorted auxiliary
    // array, let position be the index
    // where element x is in
    // auxiliary array.
    int position
        = lower_bound(aux_arr.begin(),
                      aux_arr.end(),
                      make_pair(x, 0))
          - aux_arr.begin();
 
    if (position < n
        && aux_arr[position].first == x) {
 
        // Return index of element in
        // original array arr
        // (aux_array[position].second).
        return aux_arr[position].second;
    }
    else {
        return -1;
    }
}
 
// Print Function
void print(int arr[], int n, int x)
{
    make_aux_array(arr, n);
    int result = binarySearch(arr, n, x);
 
    if (result == -1) {
        cout << -1 << endl;
    }
    else {
        cout << result << endl;
    }
}
 
// Driver code
int main()
{
    int arr[] = { 15, 12, 13, 19, 11,
                  10, 18, 17, 14, 16 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int X = 18;
 
    // Function call
    print(arr, N, X);
    return 0;
}


C




// C program to implement above approach
 
#include <stdio.h>
#include <stdlib.h>
 
// Structure to make a pair
typedef struct {
    int value, index;
} pair;
 
// Function to compare pairs
int cmp_pair(const void* a, const void* b)
{
    return ((*(pair*)a).value
            - (*(pair*)b).value);
}
 
pair* aux_arr;
 
// Function to make auxiliary array
void make_aux_array(int arr[], int n)
{
    aux_arr = (pair*)malloc(n * sizeof(pair));
 
    // For every element in array
    // write elements and
    // their indices in auxiliary array
    for (int i = 0; i < n; i++) {
        aux_arr[i].value = arr[i];
        aux_arr[i].index = i;
    }
 
    // Sort auxiliary array.
    qsort(aux_arr, n, sizeof(pair),
          cmp_pair);
}
 
// Function to implement binary search
int binarySearch(int arr[], int n, int x)
{
    // For given value x perform Binary Search
    // on sorted auxiliary array.
    // Let position be the index where
    // element x is in auxiliary array.
    pair key = { x, 0 };
    pair* found = (pair*)bsearch(
        &key, aux_arr, n, sizeof(pair), cmp_pair);
    if (found != NULL) {
        int position = found - aux_arr;
 
        // Return index of element
        // in original array arr
        // (aux_array[position].second).
        return aux_arr[position].index;
    }
    else {
        return -1;
    }
}
 
// Driver code
int main()
{
    int arr[] = { 15, 12, 13, 19, 11,
                  10, 18, 17, 14, 16 };
    int x = 18;
    int n = sizeof(arr) / sizeof(arr[0]);
    make_aux_array(arr, n);
 
    // Function call
    int result = binarySearch(arr, n, x);
    printf("%d\n", result);
    return 0;
}


Java




// Java program for the above approach:
import java.util.*;
 
// User defined Pair class
class Pair {
  int first;
  int second;
 
  // Constructor
  public Pair(int x, int y)
  {
    this.first = x;
    this.second = y;
  }
}
 
class GFG {
 
  static ArrayList<Pair> aux_arr;
 
  // Function to make auxiliary array
  static void make_aux_array(int arr[], int n)
  {
    aux_arr = new ArrayList<Pair>();
 
    // For every element in array write
    // elements and their indices in
    // auxiliary array of pairs.
    for (int i = 0; i < n; i++) {
      aux_arr.add(new Pair(arr[i], i));
    }
 
    // Sort auxiliary array in non increasing
    // order
    aux_arr.sort((a, b) -> (-a.first + b.first));
  }
 
  // Function to perform binary search
  static int binarySearch(int arr[], int n, int x)
  {
    // For given value x perform
    // Binary Search on sorted auxiliary
    // array, let position be the index
    // where element x is in
    // auxiliary array.
 
    int position = aux_arr.size() - 1;
 
    for (int i = 0; i < aux_arr.size(); i++) {
      Pair elem = aux_arr.get(i);
      if (elem.first >= x && elem.second >= 0)
        position = i;
    }
 
    if (position < n
        && aux_arr.get(position).first == x) {
 
      // Return index of element in
      // original array arr
      // (aux_array[position].second).
      return aux_arr.get(position).second;
    }
    else {
      return -1;
    }
  }
 
  // Print Function
  static void print(int arr[], int n, int x)
  {
    make_aux_array(arr, n);
    int result = binarySearch(arr, n, x);
 
    if (result == -1) {
      System.out.println(-1);
    }
    else {
      System.out.println(result);
    }
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[] arr
      = { 15, 12, 13, 19, 11, 10, 18, 17, 14, 16 };
    int N = arr.length;
    int X = 18;
 
    // Function call
    print(arr, N, X);
  }
}
 
// This code is contributed by phasing17


Python3




# Python3 program for the above approach
aux_arr = []
 
# Function to make auxiliary array
def make_aux_array(arr, n):
    global aux_arr
 
    # For every element in array write
    # elements and their indices in
    # auxiliary array of pairs
    for i in range(n):
        aux_arr.append([arr[i], i])
         
    # sort auxiliary array
    aux_arr.sort()
 
# Function to perform binary search
def binarySearch(arr, n, x):
    global aux_arr
     
    # For given value x perform
    # Binary Search on sorted auxiliary
    # array, let position be the index
    # where element x  or the element
    # just greater than x
    # is in auxiliary array
    position = n
    for i in range(n):
        if aux_arr[i][0] == x:
            position = i
             
            # return index of element in
            # original array arr
            # aux_array[position][1]
            return aux_arr[position][1]
    return -1
 
# print function
def printFunc(arr, n, x):
    global aux_arr
    make_aux_array(arr, n)
    result = binarySearch(arr, n, x)
 
    if result == -1:
        print(-1)
    else:
        print(result)
 
# Driver Code
arr = [15, 12, 13, 19, 11, 10, 18, 17, 14, 16]
N = len(arr)
X = 18
 
# Function call
printFunc(arr, N, X)
 
# This code is contributed by phasing17.


Javascript




// JavaScript program for the above approach
let aux_arr = [];
 
// Function to make auxiliary array
function make_aux_array(arr, n)
{
  // For every element in array write
  // elements and their indices in
  // auxiliary array of pairs
  for (let i = 0; i < n; i++) {
    aux_arr.push([arr[i], i]);
  }
 
  // sort auxiliary array
  aux_arr.sort();
}
 
// Function to perform binary search
function binarySearch(arr, n, x) {
  // For given value x perform
  // Binary Search on sorted auxiliary
  // array, let position be the index
  // where element x  or the element
  // just greater than x
  // is in auxiliary array
  let position = n;
  for (let i = 0; i <= n; i++) {
    if (aux_arr[i][0] == x) {
      position = i;
 
      // return index of element in
      // original array arr
      // aux_array[position][1]
      return aux_arr[position][1];
    }
  }
  return -1;
}
 
// print function
function print(arr, n, x) {
  make_aux_array(arr, n);
  let result = binarySearch(arr, n, x);
 
  if (result == -1) console.log(-1);
  else console.log(result);
}
 
// Driver Code
let arr = [15, 12, 13, 19, 11, 10, 18, 17, 14, 16];
let n = arr.length;
let x = 18;
 
// Function call
print(arr, n, x);
 
// This code is contributed by Ishan Khandelwal.


C#




using System;
using System.Collections.Generic;
 
namespace ConsoleApp
{
    class Program
    {
        static List<int[]> auxArr = new List<int[]>();
         
        static void Main(string[] args)
        {
            int[] arr = { 15, 12, 13, 19, 11, 10, 18, 17, 14, 16 };
            int N = arr.Length;
            int X = 18;
  
            MakeAuxArray(arr, N);
            int result = BinarySearch(arr, N, X);
  
            if (result == -1)
            {
                Console.WriteLine(-1);
            }
            else
            {
                Console.WriteLine(result);
            }
        }
  
        // Function to make auxiliary array
        static void MakeAuxArray(int[] arr, int n)
        {
            // For every element in array write
            // elements and their indices in
            // auxiliary array of pairs
            for (int i = 0; i < n; i++)
            {
                auxArr.Add(new int[] { arr[i], i });
            }
  
            // sort auxiliary array
            auxArr.Sort((x, y) => x[0].CompareTo(y[0]));
        }
  
        // Function to perform binary search
        static int BinarySearch(int[] arr, int n, int x)
        {
            // For given value x perform
            // Binary Search on sorted auxiliary
            // array, let position be the index
            // where element x  or the element
            // just greater than x
            // is in auxiliary array
            int position = n;
            for (int i = 0; i < n; i++)
            {
                if (auxArr[i][0] == x)
                {
                    position = i;
  
                    // return index of element in
                    // original array arr
                    // aux_array[position][1]
                    return auxArr[position][1];
                }
            }
            return -1;
        }
    }
}


Output

6

Time complexity: O(N*log N)

  • Sorting auxiliary array O(N* log N)
  • Binary Search O(log N) 

Auxiliary Space: O(N)

Conclusion: It can be seen from the workaround that using binary search takes more time compared to linear search and also uses extra space. So it is Not Recommended to use binary search for an unsorted array.


My Personal Notes arrow_drop_up
Last Updated : 17 Feb, 2023
Like Article
Save Article
Similar Reads
Related Tutorials