рефераты конспекты курсовые дипломные лекции шпоры

Реферат Курсовая Конспект

Binary Search

Binary Search - раздел Образование, Unit 4. Sorting, Searching, and Complexity · 4.1 Sorting and Searching · 4.2 Complexity Assessments · Multiple-Choice Quiz A Binary Search Is A Fast Search Algorithm Suitable For Data Sets Of Any Reas...

A binary search is a fast search algorithm suitable for data sets of any reasonable size encountered. Unlike a linear search, it is suitable even for very large data sets because it eliminates large numbers of comparisons. A binary search differs from a linear search in that it requires sorted data to operate successfully.

We can explore how a binary search operates by considering how it would find an element in the following vector.


Figure 1 A vector containing nine elements

Given the vector pictured in Figure 1, we can use a binary search to find the element that contains the value 9. All binary searches begin by comparing the item being sought against the item in the middle of the data set. In this example, the middle element contains the value 21.


Figure 2 Selecting the middle element

The value we are seeking is 9. Since 9 is less than 21, we know that 9 must be stored in an element somewhere to the left of the middle element. With this in mind, we can safely ignore the right half of the vector and continue our search, only considering the left half of the vector. Figure 3 demonstrates this partitioning of the vector.


Figure 2 Partitioning the vector

After we partition the vector, the middle element changes. We then compare the value stored here to the value we seek. Since 5 is less than 9, we know that 9 must be stored in the right half of this partition. We can then ignore the left half of this partition, and compare against the midpoint of the right half.


Figure 4 Partitioning the vector, again

Figure 4 highlights the midpoint of the current vector partition in green. The value stored here equals the value we seek so our search is complete. For this vector, which contains nine elements, only three comparisons were needed to find the element that stored the value 9. Starting from the left side of the vector, a linear search needs only three comparisons also to find the element that stores the value 9. The real advantage of binary search appears when we consider larger data sets. The following table lists the maximum number of comparisons a binary search algorithm has to make to find any element in vectors of various sizes.

Size of vector Max comparisons
1,000
10,000
100,000
1,000,000
10,000,000
100,000,000
1,000,000,000

Table 1 Maximum comparisons of binary search

Even for a vector that contains a billion elements, a binary search algorithm needs to make at most thirty comparisons to find any element. An implementation of a binary search algorithm appears in Listing 2.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: // Finding an element in a vector using binary search template <typename T> int binary_search(const vector<T>& v, const T& item) {   int low = 0; int high = v.size() - 1; int mid;   while (low <= high) {   // find the midpoint mid = (low + high) / 2;   if (v[mid] < item) { low = mid + 1; // look in upper portion } else if (v[mid] > item) { high = mid - 1; // look in lower portion } else { return mid; // found it! } }   return -1; // item not found }
Listing 2Finding an element in a vector using a binary search

The only disadvantage of a binary search is that it requires sorted data. Without sorted data, the midpoint comparisons are meaningless and the search would incorrectly report that an element is not present in the data set. Given a vector of unsorted items, how can we sort the items so that we can use a binary search? There are many approaches that we can take. We introduce the various approaches in 4.1.2 Basic Sorting Algorithms.

Instead of relying on their own binary search implementations, C++ programmers can use the STL binary_search function. The STL binary_search interface resembles the find function interface. The only difference is that function binary_search returns a bool value indicating the success of the search. An example use of the STL binary_search appears in wordsearch.cpp. This program stores the words contained in a text file into a vector. The user then enters a word via the console. The program then performs a binary search to see if the text file contains the word. A sample text file containing the full text of Nathaniel Hawthorne's The House of the Seven Gables can be found here.

– Конец работы –

Эта тема принадлежит разделу:

Unit 4. Sorting, Searching, and Complexity · 4.1 Sorting and Searching · 4.2 Complexity Assessments · Multiple-Choice Quiz

На сайте allrefs.net читайте: "Unit 4. Sorting, Searching, and Complexity · 4.1 Sorting and Searching · 4.2 Complexity Assessments · Multiple-Choice Quiz"

Если Вам нужно дополнительный материал на эту тему, или Вы не нашли то, что искали, рекомендуем воспользоваться поиском по нашей базе работ: Binary Search

Что будем делать с полученным материалом:

Если этот материал оказался полезным ля Вас, Вы можете сохранить его на свою страничку в социальных сетях:

Все темы данного раздела:

Sorting Overview
Many different basic sorting algorithms exist. Each of these algorithms has unique characteristics, behaviors, and requirements. For example, for the same set of data, one algorithm may perform far

Selection Sort
Selection sort is a basic sorting algorithm that works by making iterations, or passes, through the data being sorted. Each pass results in the placement of one element into its correct location. A

Binary поиск
Binary поиск считается быстрым алгоритмом поиска, подходит для наборов данных любого разумного размера. В отличие от линейного поиска, может использоваться даже для очень больших наборов данных, по

Краткий обзор
Существуют много различных алгоритмов сортировки. У каждого из этих алгоритмов есть уникальные характеристики, поведения, и требования. Например, для одной и той же задачи, один алгоритм может выпо

Selection Sort (Вид выбора)
Алгоритм selection sort является основным алгоритмом сортировки, который работает посредством итерации, или передачи сортируемых данных. Каждая передача приводит к перемещению одного элемента в его

Алгоритм
Quicksort является быстрым алгоритмом сортировки, который решает задачу используя проблему divide-and-conquer (разделяй и властвуй). Quicksort это рекурсия приводит массив элементов к элементарному

Реализация
Код quicksort реализации приведен в листинге 1. Эта quicksort реализация использует основную стратегию выбора центра как выбор среднего элемента. Это простой подход к реализации, и иногда он может

Использование функции сортировки STL
Стандартная библиотека шаблонов включает функции, которые программисты могут использовать, чтобы сортировать массивы контейнеров. Одна из этих функций sort функция. Функция sort выполняет быстрый s

Краткий обзор Хэш-таблиц
Хэш-таблица это структура данных ассоциативного массива, которая поддерживает очень быструю вставку элементов, удаление, и извлечение. Т.е. она позволяет хранить пары (ключ, значение) и выпо

Хеш-функции
Операции использующие хэш-таблицы эффективны, потому что позиция хранимой суммы может быть вычислена, используя ключ. Хэш-таблицы обычно реализуются как массив значений, а хеш-функция исполь

Реализация Хэш-таблицы
Следующий файл заголовочного файла и реализации объявляет и определяет шаблонный класс сопоставления хеша. Класс берет четыре шаблонных параметра. Первым является ключевой тип, и вторым является ти

The Algorithm
Quicksort is a fast sorting algorithm that uses a divide-and-conquer problem solving approach. Unlike the basic sorting algorithms we have already examined, quicksort uses recursion. Given an array

An Implementation
A quicksort implementation appears in Listing 1. This quicksort implementation uses a basic pivot selection strategy of selecting the middle element. This is a simple approach to implement, but one

Using the STL Sorting Functions
The Standard Template Library includes functions that programmers can use to sort a variety of containers. One of these functions is the sort function. The sort function performs a fast sort (typic

Overview of Hash Tables
A hash table is a data structure that supports very fast element insertion, removal, and retrieval. A hash table that is properly configured for the elements it contains can support these op

Hash Functions
Operations using hash tables are efficient because the position of a stored value can be calculated using the key. Hash tables are implemented typically as an array of values. A hash function

A Hash Table Implementation
The following header file and implementation file declares and defines a template hash map class. The class takes four template parameters. The first is the key type and the second is the value typ

Хотите получать на электронную почту самые свежие новости?
Education Insider Sample
Подпишитесь на Нашу рассылку
Наша политика приватности обеспечивает 100% безопасность и анонимность Ваших E-Mail
Реклама
Соответствующий теме материал
  • Похожее
  • Популярное
  • Облако тегов
  • Здесь
  • Временно
  • Пусто
Теги