Open In App

Binary search in an object Array for the field of an element

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

What is Binary Searching?

Binary searching is a type of algorithm that can quickly search through a sorted array of elements. The algorithm works by comparing the search key to the middle element of the array. If the key is larger than the middle element, the algorithm will search the right side of the array. If the key is smaller than the middle element, the algorithm will search the left side of the array. This process is repeated until the key is found or the array is exhausted.

What is an Object Array?

An object array is an array of objects, which is a data structure consisting of a collection of related data items. Each object in the array has a specific set of properties, and each property can contain a different type of data. 
For example, an object array might contain objects representing people, where each object has a name, age, and gender property. Object arrays are useful for storing and retrieving data. They can be used to store records of data, such as customer information, or to store and retrieve complex data structures, such as trees or graphs.

Why Use Binary Searching on Object Arrays?

Object arrays are collections of objects that have an associated “key”. In other words, a key is a field or property of the object that can be used to identify the object. 
For example, if you have an array of people, you could use the person’s name as the key. When you use binary searching on object arrays, you can quickly and accurately find the object that contains the key you’re searching for.

How to Set Up the Array for Binary Searching?

Before you can perform a binary search on an object array, you must first set up the array so that it is sorted. This is done by comparing the elements in the array and arranging them in order of their field. 
For example, if you are searching for an element with a specific name, you must arrange the elements in the array in alphabetical order by name.
Once, the array is sorted, you can begin searching for the element.

Steps Involved in Performing a Binary Search

Binary searching an object array involves the following steps:

  1. Determine the field of the element you are searching for. This can be done by looking at the properties of the objects in the array.
  2. Find the midpoint of the array. This is done by taking the length of the array and dividing it by two.
  3. Compare the element at the midpoint with the field of the element you are searching for.
  4. If the element at the midpoint matches the field of the element you are searching for, you have found the element.
  5. If the element at the midpoint does not match the field of the element you are searching for, split the array into two halves and repeat the process on one of the halves.
  6. Continue this process until you find the element or until the array is empty.

Example:

const arr = [
    {name: “John”, age: 25},
    {name: “Tim”, age: 28},
    {name: “Michelle”, age: 21},
    {name: “Alice”, age: 29}
]

here we want to search age of the Alice, pseudo code for the same is explained below:

Pseudo code:

// sort array by age
arr.sort((a, b) => a.age – b.age);

// perform binary search
function binarySearch(arr, target) {

    let low = 0;
    let high =  arr.length – 1;

    while (low <= high) {
        let mid = Math.floor((low + high) / 2);
        let guess = arr[mid];
        if (guess.name === target) {

             // return age if name matches target
             return guess.age;
         }  
        else if (guess.name > target) {
            high = mid – 1;
        } 
        else{
            low = mid + 1;
        }
    }
    return -1;
}

// search for Alice

binarySearch(arr, “Alice”); // 29

C++




#include <iostream>
#include <vector>
#include <algorithm>
 
struct Person {
    std::string name;
    int age;
};
 
// Comparator function for sorting by name
bool compareByName(const Person& a, const Person& b) {
    return a.name < b.name;
}
 
// Binary search function
int binarySearch(const std::vector<Person>& arr, const std::string& target) {
    int low = 0;
    int high = arr.size() - 1;
 
    while (low <= high) {
        int mid = (low + high) / 2;
        const Person& guess = arr[mid];
 
        if (guess.name == target) {
            // Return age if the name matches the target
            return guess.age;
        } else if (guess.name > target) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
 
    return -1; // Not found
}
 
int main() {
 
    std::vector<Person> arr = {{"John", 25}, {"Alice", 29}, {"Bob", 22}};
 
    // Sort array by name
    std::sort(arr.begin(), arr.end(), compareByName);
 
    // Perform binary search
    int result = binarySearch(arr, "Alice");
 
    // Output the result
    if (result != -1) {
        std::cout << "Age of Alice: " << result << std::endl;
    } else {
        std::cout << "Alice not found in the array." << std::endl;
    }
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
class Person {
    String name;
    int age;
 
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
 
public class Main {
 
    // Comparator for sorting by name
    static class CompareByName implements Comparator<Person> {
        @Override
        public int compare(Person a, Person b) {
            return a.name.compareTo(b.name);
        }
    }
 
    // Binary search function
    static int binarySearch(List<Person> arr, String target) {
        int low = 0;
        int high = arr.size() - 1;
 
        while (low <= high) {
            int mid = (low + high) / 2;
            Person guess = arr.get(mid);
 
            if (guess.name.equals(target)) {
                // Return age if the name matches the target
                return guess.age;
            } else if (guess.name.compareTo(target) > 0) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
 
        return -1; // Not found
    }
 
    public static void main(String[] args) {
        List<Person> arr = new ArrayList<>();
        arr.add(new Person("John", 25));
        arr.add(new Person("Alice", 29));
        arr.add(new Person("Bob", 22));
 
        // Sort array by name
        Collections.sort(arr, new CompareByName());
 
        // Perform binary search
        int result = binarySearch(arr, "Alice");
 
        // Output the result
        if (result != -1) {
            System.out.println("Age of Alice: " + result);
        } else {
            System.out.println("Alice not found in the array.");
        }
    }
}


Python3




class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
# Comparator function for sorting by name
def compare_by_name(a, b):
    return a.name < b.name
 
# Binary search function
def binary_search(arr, target):
    low = 0
    high = len(arr) - 1
 
    while low <= high:
        mid = (low + high) // 2
        guess = arr[mid]
 
        if guess.name == target:
            # Return age if the name matches the target
            return guess.age
        elif guess.name > target:
            high = mid - 1
        else:
            low = mid + 1
 
    return -1 
 
if __name__ == "__main__":
    arr = [Person("John", 25), Person("Alice", 29), Person("Bob", 22)]
 
    # Sort array by name
    arr.sort(key=lambda x: x.name)
 
    # Perform binary search
    result = binary_search(arr, "Alice")
 
    if result != -1:
        print("Age of Alice:", result)
    else:
        print("Alice not found in the array.")


C#




using System;
using System.Collections.Generic;
 
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
 
class Program
{
    // Binary search function
    static int BinarySearch(List<Person> arr, string target)
    {
        int low = 0;
        int high = arr.Count - 1;
 
        while (low <= high)
        {
            int mid = (low + high) / 2;
            Person guess = arr[mid];
 
            if (guess.Name == target)
            {
                // Return age if the name matches the target
                return guess.Age;
            }
            else if (string.Compare(guess.Name, target, StringComparison.Ordinal) > 0)
            {
                high = mid - 1;
            }
            else
            {
                low = mid + 1;
            }
        }
 
        return -1; // Not found
    }
 
    static void Main()
    {
        List<Person> arr = new List<Person>
        {
            new Person { Name = "John", Age = 25 },
            new Person { Name = "Alice", Age = 29 },
            new Person { Name = "Bob", Age = 22 }
        };
 
        // Sort list by name using lambda expression
        arr.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
 
        // Perform binary search
        int result = BinarySearch(arr, "Alice");
 
        if (result != -1)
        {
            Console.WriteLine("Age of Alice: " + result);
        }
        else
        {
            Console.WriteLine("Alice not found in the list.");
        }
    }
}


Javascript




class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}
 
// Comparator function for sorting by name
function compareByName(a, b) {
    return a.name < b.name ? -1 : 1;
}
 
// Binary search function
function binarySearch(arr, target) {
    let low = 0;
    let high = arr.length - 1;
 
    while (low <= high) {
        let mid = Math.floor((low + high) / 2);
        let guess = arr[mid];
 
        if (guess.name === target) {
            // Return age if the name matches the target
            return guess.age;
        } else if (guess.name > target) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
 
    return -1; // Not found
}
 
let arr = [new Person("John", 25), new Person("Alice", 29), new Person("Bob", 22)];
 
// Sort array by name
arr.sort(compareByName);
 
// Perform binary search
let result = binarySearch(arr, "Alice");
 
if (result !== -1) {
    console.log("Age of Alice: " + result);
} else {
    console.log("Alice not found in the array.");
}


Output

Age of Alice: 29



Time Complexity: O(log n).
Auxiliary Space: O(1).

Conclusion:

Binary searching an object array is a powerful tool for quickly and accurately retrieving data. By using binary searching on a sorted array, you can quickly find the object that contains the key you’re searching for. Implementing binary searching with object arrays requires sorting the array first, then using the binary search algorithm to find the index of the object. Once the index is found, you can access the object from the array. With binary searching, you can save time and energy when working with large amounts of data. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads