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;
};
bool compareByName( const Person& a, const Person& b) {
return a.name < b.name;
}
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 guess.age;
} else if (guess.name > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
int main() {
std::vector<Person> arr = {{ "John" , 25}, { "Alice" , 29}, { "Bob" , 22}};
std::sort(arr.begin(), arr.end(), compareByName);
int result = binarySearch(arr, "Alice" );
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 {
static class CompareByName implements Comparator<Person> {
@Override
public int compare(Person a, Person b) {
return a.name.compareTo(b.name);
}
}
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 guess.age;
} else if (guess.name.compareTo(target) > 0 ) {
high = mid - 1 ;
} else {
low = mid + 1 ;
}
}
return - 1 ;
}
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 ));
Collections.sort(arr, new CompareByName());
int result = binarySearch(arr, "Alice" );
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
def compare_by_name(a, b):
return a.name < b.name
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 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 )]
arr.sort(key = lambda x: x.name)
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
{
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 guess.Age;
}
else if ( string .Compare(guess.Name, target, StringComparison.Ordinal) > 0)
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return -1;
}
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 }
};
arr.Sort((a, b) => string .Compare(a.Name, b.Name, StringComparison.Ordinal));
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;
}
}
function compareByName(a, b) {
return a.name < b.name ? -1 : 1;
}
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 guess.age;
} else if (guess.name > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
let arr = [ new Person( "John" , 25), new Person( "Alice" , 29), new Person( "Bob" , 22)];
arr.sort(compareByName);
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...