Open In App

Binary search in sorted vector of pairs

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

How to apply STL binary_search to vector of pairs(key, value), given that vector is sorted by its first value(key) struct compare in the code contains two functions which compares the key(searching element) with the first element in the vector 

CPP




/* C++ code to demonstrate how Binary Search
can be applied on a vector of pairs */
#include <bits/stdc++.h>
using namespace std;
 
struct compare {
 bool operator()(const pair<int, int>& value,
        const int& key)
 {
  return (value.first < key);
 }
 bool operator()(const int& key,
     const pair<int, int>& value)
 {
  return (key < value.first);
 }
};
 
int main()
{
 // initializing the vector of pairs
 vector<pair<int, int> > vect;
 
 // insertion of pairs (key, value) in vector vect
 vect.push_back(make_pair(1, 20));
 vect.push_back(make_pair(3, 42));
 vect.push_back(make_pair(4, 36));
 vect.push_back(make_pair(2, 80));
 vect.push_back(make_pair(7, 50));
 vect.push_back(make_pair(9, 20));
 vect.push_back(make_pair(3, 29));
 
 // sorting the vector according to key
 sort(vect.begin(), vect.end());
 
 // printing the sorted vector
 cout << "KEY" << '\t' << "ELEMENT" << endl;
 for (pair<int, int>& x : vect)
  cout << x.first << '\t' << x.second << endl;
 
 // searching for the key element 3
 cout << "search for key 3 in vector" << endl;
 if (binary_search(vect.begin(), vect.end(),
        3, compare()))
  cout << "Element found";
 else
  cout << "Element not found";
 
 return 0;
}


Java




import java.util.*;
 
class Main {
    public static void main(String[] args) {
        // initializing the vector of pairs
        Vector<Pair<Integer, Integer>> vector = new Vector<>();
 
        // insertion of pairs (key, value) in vector
        vector.add(new Pair<>(1, 20));
        vector.add(new Pair<>(3, 42));
        vector.add(new Pair<>(4, 36));
        vector.add(new Pair<>(2, 80));
        vector.add(new Pair<>(7, 50));
        vector.add(new Pair<>(9, 20));
        vector.add(new Pair<>(3, 29));
 
        // sorting the vector according to key and then value
        vector.sort((p1, p2) -> {
            if (!p1.getKey().equals(p2.getKey())) {
                return p1.getKey().compareTo(p2.getKey());
            } else {
                return p1.getValue().compareTo(p2.getValue());
            }
        });
 
        // printing the sorted vector
        System.out.println("KEY\tELEMENT");
        for (Pair<Integer, Integer> pair : vector) {
            System.out.println(pair.getKey() + "\t" + pair.getValue());
        }
 
        // searching for the key element 3
        System.out.println("search for key 3 in vector");
        if (Collections.binarySearch(vector, new Pair<>(3, 0), Comparator.comparing(Pair::getKey)) >= 0) {
            System.out.println("Element found");
        } else {
            System.out.println("Element not found");
        }
    }
}
 
class Pair<K, V> {
    private K key;
    private V value;
 
    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }
 
    public K getKey() {
        return key;
    }
 
    public V getValue() {
        return value;
    }
}


C#




using System;
using System.Collections.Generic;
 
class MainClass
{
    public static void Main(string[] args)
    {
        // Initializing the vector of pairs
        List<Pair<int, int>> vector = new List<Pair<int, int>>();
 
        // Insertion of pairs (key, value) in the vector
        vector.Add(new Pair<int, int>(1, 20));
        vector.Add(new Pair<int, int>(3, 42));
        vector.Add(new Pair<int, int>(4, 36));
        vector.Add(new Pair<int, int>(2, 80));
        vector.Add(new Pair<int, int>(7, 50));
        vector.Add(new Pair<int, int>(9, 20));
        vector.Add(new Pair<int, int>(3, 29));
 
        // Sorting the vector according to key and then value
        vector.Sort((p1, p2) => {
            if (!p1.GetKey().Equals(p2.GetKey()))
            {
                return p1.GetKey().CompareTo(p2.GetKey());
            }
            else
            {
                return p1.GetValue().CompareTo(p2.GetValue());
            }
        });
 
        // Printing the sorted vector
        Console.WriteLine("KEY\tELEMENT");
        foreach (Pair<int, int> pair in vector)
        {
            Console.WriteLine(pair.GetKey() + "\t" + pair.GetValue());
        }
 
        // Searching for the key element 3
        Console.WriteLine("Search for key 3 in vector");
        if (BinarySearch(vector, new Pair<int, int>(3, 0), Comparer<Pair<int, int>>.Create((p1, p2) => p1.GetKey().CompareTo(p2.GetKey()))) >= 0)
        {
            Console.WriteLine("Element found");
        }
        else
        {
            Console.WriteLine("Element not found");
        }
    }
 
    // Binary search with custom comparator
    static int BinarySearch(List<Pair<int, int>> list, Pair<int, int> key, IComparer<Pair<int, int>> comparer)
    {
        int left = 0, right = list.Count - 1;
 
        while (left <= right)
        {
            int mid = left + (right - left) / 2;
 
            // Check if key is found at mid index
            int comparisonResult = comparer.Compare(list[mid], key);
 
            if (comparisonResult < 0)
                left = mid + 1;
            else if (comparisonResult > 0)
                right = mid - 1;
            else
                return mid;
        }
 
        return -1; // Key not found
    }
}
 
// Pair class with generic Key and Value
class Pair<K, V>
{
    private K key;
    private V value;
 
    public Pair(K key, V value)
    {
        this.key = key;
        this.value = value;
    }
 
    public K GetKey()
    {
        return key;
    }
 
    public V GetValue()
    {
        return value;
    }
}


Javascript




// Define a comparison function to use in binary search
function compare(value, key) {
    return value[0] < key;
}
 
// Define a comparison function to use in binary search
function compare2(key, value) {
    return key < value[0];
}
 
// Binary search implementation
function binarySearch(arr, key) {
    let start = 0;
    let end = arr.length - 1;
 
    while (start <= end) {
        let mid = Math.floor((start + end) / 2);
 
        if (compare(arr[mid], key))
            start = mid + 1;
        else if (compare2(key, arr[mid]))
            end = mid - 1;
        else
            return true;
    }
 
    return false;
}
 
// Main function
(function main() {
    // initializing the array of pairs
    let vect = [
        [1, 20],
        [2, 80],
        [3, 29],
        [3, 42],
        [4, 36],
        [7, 50],
        [9, 20]
    ];
 
    // sorting the array according to the first element
    vect.sort((a, b) => a[0] - b[0]);
 
    // printing the sorted array
    console.log("KEY", "ELEMENT");
    for (let x of vect) {
        console.log(x[0], x[1]);
    }
 
    // searching for the key element 3
    console.log("Search for key 3 in array:");
    if (binarySearch(vect, 3))
        console.log("Element found");
    else
        console.log("Element not found");
})();


Python3




def binary_search(vect, key):
    left, right = 0, len(vect) - 1
 
    while left <= right:
        mid = left + (right - left) // 2
        if vect[mid][0] == key:
            return mid
        elif vect[mid][0] < key:
            left = mid + 1
        else:
            right = mid - 1
 
    return -1
 
 
# Initializing the list of tuples
vect = []
 
# Insertion of tuples (key, value) in list vect
vect.append((1, 20))
vect.append((3, 42))
vect.append((4, 36))
vect.append((2, 80))
vect.append((7, 50))
vect.append((9, 20))
vect.append((3, 29))
 
# Sorting the list according to key
vect.sort()
 
# Printing the sorted list
print("KEY", "\t", "ELEMENT")
for x in vect:
    print(x[0], "", x[1])
 
# Searching for the key element 3
print("Search for key 3 in vector")
key_to_find = 3
index = binary_search(vect, key_to_find)
if index != -1:
    print("Element found")
else:
    print("Element not found")


Output

KEY    ELEMENT
1    20
2    80
3    29
3    42
4    36
7    50
9    20
search for key 3 in vector
Element found






Time complexity: O(n log n) (As sort() function is used)

Auxiliary Space: O(1)



Last Updated : 08 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads