DEV Community

Cover image for Binary Search In Javascript: Practical Mini Project
Danities Ichaba
Danities Ichaba

Posted on

Binary Search In Javascript: Practical Mini Project

In continuation for our series Demystifying Data Structures and Algorithms: A Comprehensive Guide for Developers we are going to discuss on

Live Demo

Binary Search:

I took it upon myself to enhanced my understanding of algorithms and data structures while building practical applications? In this blog post, we will explore the implementation of an efficient contact search using the binary search algorithm in JavaScript. By combining the power of binary search and JavaScript, we'll create a phonebook application that provides lightning-fast contact retrieval. Let's dive in!

Understanding Binary Search

Binary search is a fundamental algorithm used to search for an element in a sorted list or array. It follows a divide-and-conquer approach, repeatedly dividing the search space in half until the target element is found or the search space is exhausted. With each iteration, binary search eliminates half of the remaining elements, resulting in a significantly faster search time compared to linear search.

  • Building the Phonebook Search Application
    To apply the binary search algorithm practically, we'll develop a phonebook search application using JavaScript. The application will allow users to search for contacts by name, leveraging the efficiency of the binary search algorithm.

  • Data Structure: We'll begin by creating a sorted array of contacts, containing names and corresponding phone numbers. Sorting the array ensures that the binary search algorithm can be applied efficiently.

const data = [
{"first_name":"Andee","last_name":"Ogles","phone":"(531) 8435492","gender":"Female","picture":"http://dummyimage.com/172x100.png/ff4444/ffffff"},
{"first_name":"Berri","last_name":"Kinforth","phone":"(535) 9255883","gender":"Female","picture":"http://dummyimage.com/244x100.png/dddddd/000000"},
{"first_name":"Shantee","last_name":"Sterndale","phone":"(640) 1705736","gender":"Female","picture":"http://dummyimage.com/133x100.png/5fa2dd/ffffff"}

];

const phoneBook = [];
    // Sorting or array of objects so as to run binary search
    const sortData = data.sort((a, b) => a.first_name.localeCompare(b.first_name));
    return phoneBook.push(...data);
  });

Enter fullscreen mode Exit fullscreen mode
  • Implementing Binary Search: We'll write a binary search function in JavaScript that takes the sorted array of contacts and the search query as input. The function will divide the array into smaller halves, compare the search query with the middle element, and continue the search in the appropriate half until the contact is found or the search space is exhausted.
function binarySearch(phoneBook, searchName) {
  searchName = searchName.toLowerCase();
  let low = 0;
  let high = phoneBook.length - 1;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    const contact = phoneBook[mid];
    const FirstNametoLowerCase = contact.first_name.toLowerCase(); // Convert contact name to lowercase

    if (FirstNametoLowerCase === searchName) {
      return contact;
    } else if (FirstNametoLowerCase < searchName) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }

  return null; // Contact not found
}
Enter fullscreen mode Exit fullscreen mode
  • User Interface: Next, we'll create a user-friendly interface using HTML, CSS, and JavaScript. The interface will include an input field for users to enter the name they want to search and a search button to initiate the search process.

HTML

<!DOCTYPE html>
<html>
<head>
  <title>Phonebook Search</title>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <h1>Phonebook Search</h1>
  <input type="text" id="searchInput" placeholder="Enter a name">
  <button id="searchButton">Search</button>
  <div id="resultsContainer"></div>

  <script src="script.js"></script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

CSS

body {
  font-family: Arial, sans-serif;
}

h1 {
  text-align: center;
}

input[type="text"] {
  padding: 5px;
  font-size: 16px;
}

button {
  padding: 5px 10px;
  font-size: 16px;
}

#resultsContainer {
  margin-top: 20px;
}

Enter fullscreen mode Exit fullscreen mode
  • Displaying Results: Upon clicking the search button, our application will utilize the binary search function to find the contact and display the corresponding phone number. If the contact is not found, an appropriate message will be displayed to the user.

Conclusion

By implementing a phonebook search application using the binary search algorithm in JavaScript, I have gained a deeper understanding of this efficient searching technique. Through this project, I've explored the power of algorithms in practical applications, sharpened my problem-solving skills, and honed my JavaScript programming abilities. The combination of binary search and JavaScript presents limitless possibilities for optimizing search operations in various domains.

Building projects that utilize algorithms not only enhances our technical skills but also provides valuable insights into problem-solving and algorithmic thinking. I encourage you to continue exploring algorithms and data structures to further expand your programming expertise.

I would also like to to experiment with additional features, such as pagination, fuzzy searching, or incorporating other algorithms into this project. Stay with me to discover and continuous learning as you apply algorithms to real-world scenarios. Happy coding!

Live Demo

Top comments (0)