Binary search in an object Array for the field of an element
Last Updated :
02 Feb, 2024
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:
- 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.
- Find the midpoint of the array. This is done by taking the length of the array and dividing it by two.
- Compare the element at the midpoint with the field of the element you are searching for.
- If the element at the midpoint matches the field of the element you are searching for, you have found the element.
- 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.
- 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.");
}
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.
Similar Reads
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
What is Binary Search Algorithm?
Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half and the correct interval to find is decided based on the searched value and the mid value of the interval. Example of binary searchProperties of Binary Search:Binary search is performed o
1 min read
Time and Space Complexity Analysis of Binary Search Algorithm
Time complexity of Binary Search is O(log n), where n is the number of elements in the array. It divides the array in half at each step. Space complexity is O(1) as it uses a constant amount of extra space. Example of Binary Search AlgorithmAspectComplexityTime ComplexityO(log n)Space ComplexityO(1)
3 min read
How to calculate "mid" or Middle Element Index in Binary Search?
The most common method to calculate mid or middle element index in Binary Search Algorithm is to find the middle of the highest index and lowest index of the searchable space, using the formula mid = low + \frac{(high - low)}{2} Finding the middle index "mid" in Binary Search AlgorithmIs this method
6 min read
Variants of Binary Search
Variants of Binary Search
Binary search is very easy right? Well, binary search can become complex when element duplication occurs in the sorted list of values. It's not always the "contains or not" we search using Binary Search, but there are 5 variants such as below:1) Contains (True or False)Â 2) Index of first occurrence
15+ min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta B
9 min read
The Ubiquitous Binary Search | Set 1
We are aware of the binary search algorithm. Binary search is the easiest algorithm to get right. I present some interesting problems that I collected on binary search. There were some requests on binary search. I request you to honor the code, "I sincerely attempt to solve the problem and ensure th
15+ min read
Uniform Binary Search
Uniform Binary Search is an optimization of Binary Search algorithm when many searches are made on same array or many arrays of same size. In normal binary search, we do arithmetic operations to find the mid points. Here we precompute mid points and fills them in lookup table. The array look-up gene
7 min read
Randomized Binary Search Algorithm
We are given a sorted array A[] of n elements. We need to find if x is present in A or not.In binary search we always used middle element, here we will randomly pick one element in given range.In Binary Search we had middle = (start + end)/2 In Randomized binary search we do following Generate a ran
13 min read
Abstraction of Binary Search
What is the binary search algorithm? Binary Search Algorithm is used to find a certain value of x for which a certain defined function f(x) needs to be maximized or minimized. It is frequently used to search an element in a sorted sequence by repeatedly dividing the search interval into halves. Begi
7 min read
N-Base modified Binary Search algorithm
N-Base modified Binary Search is an algorithm based on number bases that can be used to find an element in a sorted array arr[]. This algorithm is an extension of Bitwise binary search and has a similar running time. Examples: Input: arr[] = {1, 4, 5, 8, 11, 15, 21, 45, 70, 100}, target = 45Output:
10 min read
Implementation of Binary Search in different languages
C Program for Binary Search
In this article, we will understand the binary search algorithm and how to implement binary search programs in C. We will see both iterative and recursive approaches and how binary search can reduce the time complexity of the search operation as compared to linear search.Table of ContentWhat is Bina
7 min read
C++ Program For Binary Search
Binary Search is a popular searching algorithm which is used for finding the position of any given element in a sorted array. It is a type of interval searching algorithm that keep dividing the number of elements to be search into half by considering only the part of the array where there is the pro
5 min read
C Program for Binary Search
In this article, we will understand the binary search algorithm and how to implement binary search programs in C. We will see both iterative and recursive approaches and how binary search can reduce the time complexity of the search operation as compared to linear search.Table of ContentWhat is Bina
7 min read
Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)
In C++, STL provide various functions like std::binary_search(), std::lower_bound(), and std::upper_bound() which uses the the binary search algorithm for different purposes. These function will only work on the sorted data.There are the 3 binary search function in C++ STL:Table of Contentbinary_sea
3 min read
Binary Search in Java
Binary search is a highly efficient searching algorithm used when the input is sorted. It works by repeatedly dividing the search range in half, reducing the number of comparisons needed compared to a linear search. Here, we are focusing on finding the middle element that acts as a reference frame t
6 min read
Binary Search (Recursive and Iterative) - Python
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Below is the step-by-step algorithm for Binary Search:D
6 min read
Binary Search In JavaScript
Binary Search is a searching technique that works on the Divide and Conquer approach. It is used to search for any element in a sorted array. Compared with linear, binary search is much faster with a Time Complexity of O(logN), whereas linear search works in O(N) time complexityExamples: Input : arr
3 min read
Binary Search using pthread
Binary search is a popular method of searching in a sorted array or list. It simply divides the list into two halves and discards the half which has zero probability of having the key. On dividing, we check the midpoint for the key and use the lower half if the key is less than the midpoint and the
8 min read
Comparison with other Searching
Binary Search Intuition and Predicate Functions
The binary search algorithm is used in many coding problems, and it is usually not very obvious at first sight. However, there is certainly an intuition and specific conditions that may hint at using binary search. In this article, we try to develop an intuition for binary search. Introduction to Bi
12 min read
Can Binary Search be applied in an Unsorted Array?
Binary Search is a search algorithm that 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 comp
9 min read
Find a String in given Array of Strings using Binary Search
Given a sorted array of Strings arr and a string x, The task is to find the index of x in the array using the Binary Search algorithm. If x is not present, return -1.Examples:Input: arr[] = {"contribute", "geeks", "ide", "practice"}, x = "ide"Output: 2Explanation: The String x is present at index 2.
6 min read