Computer Science

Binary Search

Binary search is a search algorithm that works by dividing a sorted array into two halves and repeatedly comparing the middle element of each half with the target value. The search continues on the half of the array where the target value may be located until the value is found or the search is exhausted. It has a time complexity of O(log n).

Written by Perlego with AI-assistance

10 Key excerpts on "Binary Search"

  • Book cover image for: Data Structures and Program Design Using C
    No longer available |Learn more

    Data Structures and Program Design Using C

    A Self-Teaching Introduction

    SEARCHING AND SORTING • 255 6.3 Binary Search A Binary Search is an extremely efficient searching algorithm when it is compared to a linear search. A Binary Search works only when the array/list is already sorted. In a Binary Search, we first compare the value VAL with the data element in the middle position of the array. If the match is found, then the position POS of that element is returned; otherwise, if the value is less than that of the middle element, then we begin our search in the lower half of the array and vice versa. So, we repeat this process on the lower and upper half of the array. 6.3.1 Binary Search Algorithm Let us now understand how this Binary Search algorithm works in an array. 1. Find the middle element of the array, that is, n/2 is the middle element of the array containing n elements. 2. Now, compare the middle element of the array with the data element to be searched. Frequently Asked Questions Q. Explain how a linear search technique is used to search for an element. Answer. Suppose that ARR is an array having N elements. ITEM is the value to be searched. Then we have the following cases: Case 1: Unsorted List – The ITEM is compared with every element of the array. If the element is found, then no further comparison is required. If all the elements are compared and checked, then the ITEM is not found. Case 2: Sorted List – The ITEM is greater than the first element and smaller than the last element of the list, so searching is performed by com- paring each element in the list with ITEM; otherwise, ITEM is reported as “Not Found.” 256 • DATA STRUCTURES AND PROGRAM DESIGN USING C a) If the middle element is the desired element, then the search is successful. b) If the data element to be searched for is less than the middle element of the array, then search only the lower half of the array, that is, those elements which are on the left side of the middle ele- ment.
  • Book cover image for: Beginning Algorithms
    • Simon Harris, James Ross(Authors)
    • 2008(Publication Date)
    • Wrox
      (Publisher)
    Modern software applications often deal with enormous amounts of data, and being able to search that data efficiently is important. Being able to locate a particular patient’s record quickly among tens of thousands of others can make or break an application. From now on, the chapters in this book focus largely on algorithms and data structures designed specifically for the efficient storage and searching of data. Binary Searching is one of the most basic techniques for efficiently searching through data in mem- ory. Binary insertion is a variation on Binary Searching that enables you to maintain the data such that it can be efficiently searched. This chapter discusses the following: ❑ How to perform Binary Searching ❑ Implementing a Binary Search using iteration and recursion ❑ Comparing Binary Searching with other search techniques ❑ Comparing binary insertion with other sorting techniques Understanding Binary Searching Binary Searching is a technique for locating items in a sorted list. A Binary Search takes advantage of certain characteristics of sorted lists that a simple linear search doesn’t. Indeed, whereas a brute- force linear search runs in O(N) time, a Binary Search runs in O(log N), assuming the data to be searched is sorted. As you saw in Chapter 2, the simplest way to search an unordered list is to start at the first item and con- tinue forward until you either find a match or run out of items. This leads to an average-case running time of O(N). The actual average running time is around N/2; that is, you would need to traverse, on average, half the items in the list before you found the one for which you were looking. For data that is sorted, however, you can do a lot better. Binary Searching gets its name from the fact that you continually divide the data in half, progressively narrowing down the search space until you find a match or there are no more items to process.
  • Book cover image for: Programming with C++
    • Kyla McMullen, Elizabeth Matthews, June Jamrich Parsons, , Kyla McMullen, Kyla McMullen, Elizabeth Matthews, June Jamrich Parsons(Authors)
    • 2021(Publication Date)
    The search takes a long time because as the amount of information increases, you lose time examining many contacts until you find the one you want. If your data is ordered, the search becomes easier. You can take advantage of the inherent ordering sys- tem for letters (A to Z) and for numbers (0 to 9). Suppose you are looking up the word “dog” in the diction- ary. If you open the dictionary to a page with words that begin with the letter “m,” then you know that the definition of dog is listed before this page. You do not need to look at any words that come after the letter “m” because you know the first letter in “dog” comes before “m.” In essence, you have reduced the search space by 50 percent. Search becomes easier when you can eliminate part of the search space. To take advantage of the ordering of data, you can use a Binary Search algorithm, which divides the search space in half until the target value is located. This approach is typically referred to as a divide-and-conquer technique because each step divides the search space and eliminates part of it on the path to a solution. Any data structure that uses Binary Search must have the data in the search space in sorted order. Binary Search algorithms do not work on unsorted data or data with duplicate values. An ordered collection of data, such as a dictionary, has the characteristics necessary for Binary Search. In general, any collection of data that consists of unique values that can be ordered is required for Binary Search. (For example, the dictionary does not list the same word twice.) When coding a Binary Search algorithm, you use recursion or iteration. The algorithm for Binary Search is the following: 1. Specify a cursor variable called min to point to the first element in the search space. 2. Specify a cursor variable called max to point to the last element in the search space. 3. Specify a cursor variable called current to begin at the middle of the search space, the size of the array/2.
  • Book cover image for: Data Structures and Program Design Using Python
    No longer available |Learn more
    Binary Search works only when the array/list is already sorted. In a Binary Search, we first compare the value VAL with the data element in the middle position of the array. If the match is found, then the position POS of that element is returned; otherwise, if the value is less than that of the middle element, then we begin our search in the lower half of the array and vice versa. So, we repeat this process on the lower and upper half of the array.
    6.3.1 Binary Search Algorithm
    Let us now understand how this Binary Search algorithm works in an array.
    1. Find the middle element of the array, that is, n/2 is the middle element of the array containing n elements.
    2. Now, compare the middle element of the array with the data element to be searched.
    a. If the middle element is the desired element, then the search is successful.
    b. If the data element to be searched for is less than the middle element of the array, then search only the lower half of the array, that is, those elements which are on the left side of the middle element.
    c. If the data element to be searched for is greater than the middle element of the array, then search only the upper half of the array, that is, those elements which are on the right side of the middle element.
    Repeat these steps until a match is found.
    Practical Application:
    A real-life application of a Binary Search is when we search for a particular word in a dictionary. We first open the dictionary somewhere in the middle. Now we will compare the desired word with the first word on that page. If the desired word comes after the first word on an open page, then we look in the second half of the dictionary; otherwise, we look in the first half. Now, we again open a page in the second half and compare the desired word with the first word on that page, and the same process is repeated until we have found the desired word.
  • Book cover image for: Data Structures and Program Design Using Java
    No longer available |Learn more
    A Binary Search works only when the array/list is already sorted. In a Binary Search, we first compare the value VAL with the data element in the middle position of the array. If the match is found, then the position POS of that element is returned; otherwise, if the value is less than that of the middle element, then we begin our search in the lower half of the array and vice versa. So, we repeat this process on the lower and upper half of the array.

    6.3.1  Binary Search Algorithm

    Let us now understand how this Binary Search algorithm works in an array.
    1. Find the middle element of the array, that is, n/2 is the middle element of the array containing n elements.
    2. Now, compare the middle element of the array with the data element to be searched. (a) If the middle element is the desired element, then the search is successful.
      (b) If the data element to be searched for is less than the middle element of the array, then search only the lower half of the array, that is, those elements which are on the left side of the middle element.
      (c) If the data element to be searched for is greater than the middle element of the array, then search only the upper half of the array, that is, those elements which are on the right side of the middle element.
    Repeat these steps until a match is found.  
    Practical Application
    A real-life application of a Binary Search is that when we search for a particular word in a dictionary, we first open the dictionary somewhere in the middle. Now we will compare the desired word with the first word on that page. If the desired word comes after the first word on an open page, then we will look in the second half of the dictionary; otherwise, we will look in the first half. Now, we will again open a page in the second half and compare the desired word with the first word on that page, and the same process is repeated until we have found the desired word.
  • Book cover image for: Data Structures and Program Design Using C++
    A Binary Search works only when the array/list is already sorted . In a Binary Search, we first compare the value VAL with the data element in the middle position of the array. If the match is found, then the position POS of that element is returned; otherwise, if the value is less than that of the middle element, then we begin our search in the lower half of the array and vice versa. So, we repeat this process on the lower and upper half of the array.
    6.3.1Binary Search Algorithm
    Let us now understand how this Binary Search algorithm works in an array.
    1. Find the middle element of the array, that is, n/2 is the middle element of the array containing n elements.
    2. Now, compare the middle element of the array with the data element to be searched.
    a) If the middle element is the desired element, then the search is successful.
    b) If the data element to be searched for is less than the middle element of the array, then search only the lower half of the array, that is, those elements which are on the left side of the middle element.
    c) If the data element to be searched for is greater than the middle element of the array, then search only the upper half of the array, that is, those elements which are on the right side of the middle element.
    Repeat these steps until a match is found.
    Practical Application:
    A real-life application of a Binary Search is that when we search for a particular word in a dictionary, we first open the dictionary somewhere in the middle. Now we will compare the desired word with the first word on that page. If the desired word comes after the first word on an open page, then we will look in the second half of the dictionary; otherwise, we will look in the first half. Now, we will again open a page in the second half and compare the desired word with the first word on that page, and the same process is repeated until we have found the desired word.
  • Book cover image for: Discovering Computer Science
    eBook - PDF

    Discovering Computer Science

    Interdisciplinary Problems, Principles, and Python Programming

    I Reflection 10.1 How can we apply this idea to searching a sorted list? We can search a sorted list in a similar way, except that we usually do not know much about the distribution of the list's contents, so it is hard to make that first guess about where to start. In this case, the best strategy is to start in the middle. After comparing the target item to the middle item, we continue searching in the half of the list that must contain the target alphabetically. Because we are effectively dividing the list into two halves in each step, this algorithm is called Binary Search. For example, suppose we wanted to search for the number 70 in the following sorted list of numbers. (We will use numbers instead of words in our example to save space.) left mid right  I ; I ; I ; I ; I ; I ; I ; I ; I ; I ; I I I 10 20 30 40 50 60 70 80 90 100 110 120 As we hone in on our target, we will update two variables named left and right to keep track of the first and last indices of the sublist that we are still considering. In addition, we will maintain a variable named mid that is assigned to the index of the middle value of this sublist. (When there are two middle values, we choose the 10.1 Binary Search • 409 Tangent 10.1: Databases A database is a structured file (or set of files) that contains a large amount of searchable data. The most common type of database, called a relational database, stores its data in tables. Each row in a table has a unique key that can be used to search for that row. For example, the tables below represent a small portion of the earthquake data that we worked with in Section 7.4. The key in each table is underlined. Earthquakes Networks QuakelD Latitude Longitude Mag NetlD NetID Net Name nc72076126 40.1333 -123.863 1.8 NC AK Alaska Regional ak10812068 59.8905 -151.
  • Book cover image for: Introduction to Search Algorithms
    • Rex Porbasas Flejoles(Author)
    • 2019(Publication Date)
    • Arcler Press
      (Publisher)
    An equation representing the number (n) of executed Fundamentals of Search Algorithms 7 comparisons can be formulated as: T(n) = n/c +2c – 1. Typically, we just ignore the constant number, because the constant number has no effect when n becomes higher. Finally, we get T(n) = n/c +2c (Cai et al., 1992; Chawathe et al., 1996; Caouette et al., 1998). 1.5. Binary Search Let’s consider the below discussed concept for a search algorithm employing the phone book example. Suppose, we choose a page randomly from the middle of a phonebook. If the particular name being determined is on this page, we are successful. If the particular name being determined occurs alphabetically prior to this page, the processes are repeated on the phonebook’s first half; otherwise, the process is repeated on the phonebook’s second half. It may be noted that each iteration involves the division of the remaining chunk of the phonebook to be sought into two halves; the algorithm involving such strategies is known as Binary Search (Chiueh, 1994; Christmas et al., 1995; Ciaccia et al., 1997). This algorithm may not sound like the most suitable algorithm for searching the phonebook (or an ordered list), this is possibly the quickest. This is true for many computer algorithms, i.e., the most natural (suitable) algorithm is not essentially the best (Cole & Hariharan, 1997; Clark & DeRose, 1999). A typical model for Binary Search algorithm is illustrated below: Input: an A-ordered array of objects, n-the number of elements, the x-key value being determined. Output: if found, return position i, if not, return the message “x not found.” • Divide the array into two equal halves. • Perform the comparison of x with the first half’s last element to check the equality of x with that particular element. • If yes, stop search and return the position. • If no, perform the comparison of x with the first half’s last element once again to see if the value of x is greater than that element.
  • Book cover image for: Invitation to Computer Science
    Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 126 Chapter 3 The Efficiency of Algorithms 1 or 3. Similarly, if NUMBER is not found at location 6, the next location searched is either 5 or 7. In Figure 3.18, the Binary Search algorithm, we assume in Step 5 that there is a middle position between beginning and end . This happens only when there is an odd number of elements in the list. Let us agree to define the “middle” of an even number of entries as the end of the first half of the list. With eight elements, for example, the midpoint position is location 4. 1 2 3 4 5 6 7 8 With this understanding, the Binary Search algorithm can be used on sorted lists of any size. And of course, the list items need not be numbers; they could also be text items that are sorted alphabetically. Like the sequential search algorithm, the Binary Search algorithm relies on comparisons, so to analyze the algorithm, we count the num-ber of comparisons as an indication of the work done. The best case, as in sequential search, requires only one comparison—the target is located on the first try. The worst case, as in sequential search, occurs when the target is not in the list. However, we learn this much sooner in Binary Search than in sequential search. In our list of seven telephone numbers, only three comparisons are needed to determine that 7213350096 is not in the list. The number of comparisons needed is the number of circles in some branch from the top to the bottom of the tree in Figure 3.19. These circles represent searches at the midpoints of the whole list, half the list, one quarter of the list, and so on. This process continues as long as the sublists can be cut in half. FIGURE 3.19 Binary Search tree for a seven-element list 1 3 5 7 2 6 4 NUMBER after number 4 Before number 2 After number 2 After number 6 Before number 6 NUMBER before number 4 Copyright 2019 Cengage Learning.
  • Book cover image for: The Fundamentals of algorithmic processes
    • Sourabh Pal(Author)
    • 2023(Publication Date)
    • Arcler Press
      (Publisher)
    We usually ignore the constant number since it has no effect as n increases. Ultimately, T(n) = n/c +2c is obtained (Cai et al., 1992; Caouette et al., 1998). 3.5. Binary Search Consider the following notion for a search algorithm using the phone book as an instance. Assume we pick a page from the center of a phonebook at random. We’ve succeeded if the name we’re looking for is listed on this page (Figure 3.3). The Fundamentals of Algorithmic Processes 66 Figure 3.3. Binary Search algorithm with an example. Source: https://www.guru99.com/binary-search.html. The operations are repeated on the 1 st half of the phonebook if the specific name being determined appears alphabetically before this page; alternatively, the processes are repeated on the 2 nd half of the phonebook. It should be noted that every iteration entails splitting the remaining piece of the phonebook to be searched into 2 halves; this approach is referred to as Binary Search (Chiueh, 1994; Christmas et al., 1995; Ciaccia et al., 1997). Although this technique can not appear to be the best for scanning a phonebook (or an ordered list), it is likely the fastest. This is true for several computer algorithms; the most natural (appropriate) algorithm isn’t always the best (Cole and Hariharan, 1997). The following is an example of a Binary Search algorithm model: • Input: determining the “x” key-value, n-the number of elements, an A-ordered array of objects. • Output: if found, return position “i,” if not, return the message “x not found.” • Split the array into 2 equal halves; • Check equivalence of x with the 1 st half’s final element by comparing it to that element; • If so, stop looking and return to your original location; • If no, compare the value of x to the final element of the 1 st half to check if the value of x is larger than that element; Fundamentals of Search Algorithms 67 • If yes, x must be in the 2 nd part of the equation.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.