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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem