Реферат Курсовая Конспект
Unit 4. Sorting, Searching, and Complexity · 4.1 Sorting and Searching · 4.2 Complexity Assessments · Multiple-Choice Quiz - раздел Образование, Unit 4. Sorting, Searching, And Complexity · 4.1 Sorting And...
|
Unit 4. Sorting, Searching, and Complexity
· 4.1 Sorting and Searching
· 4.2 Complexity
Assessments
· Multiple-Choice Quiz 7
· Exercise 4
4.1 Sorting and Searching
With this module, the course introduces some of the basic concepts of sorting and searching.
| |||||||
4.1.1 Linear vs. Binary Search
Searching: A Common Task
Searching for data is a common task found not just in computer science but also in the real world. In the most basic sense, finding an element stored in a vector is similar to searching for a person's name in a telephone book. In both cases, we want to find one piece of data that exists somewhere in a larger set of similar data.
In both computer science and in the real world, the process involved in searching differs depending on the arrangement of the data set being searched. If a set is arranged in no particular order, the best search process we can use is a simple pass through the set. This process involves examining every item in the set until we find the item we are seeking. This is probably an adequate solution for only small sets of data. Imagine looking for a specific card from a completely shuffled deck of cards. With only fifty-two total cards in the deck, a front-to-back pass through the deck is a valid approach to finding a specific card.
Larger sets of data require a more efficient searching approach. Imagine trying to find a person's telephone number using a telephone book that lists people in random order. Examining every listing during a front-to-back pass through the book probably would take a few days. This is definitely not an efficient approach, and is the reason why telephone book listings are alphabetized. Leveraging our knowledge of how the telephone book arranges its listings, we can perform a more efficient search. This search involves opening the telephone book and comparing the listings on the page to the listing we are seeking. If we are searching for "Doe, John", and the page we opened the book to contains only listings for "Smith", we know we must flip to another page closer to listings for "Doe". We continue this approach until we reach the page containing our listing. This search probably only takes a minute to complete. This is fast compared to the time that a front-to-back pass through the book would take.
Both of these real world approaches to searching have computer-science algorithm analogues. A front-to-back pass through a data set is known as a linear search. A more formal variant of searching through the telephone book is known as a binary search.
Linear Search
A linear search is a simple search algorithm that finds an item by examining a data set in order. A linear search is sometimes known as a sequential search. In C++, we can implement a linear search as a for-loop using only a few lines of code.
Besides the simplicity of its implementation, the main advantage of a linear search is that it does not require sorted data. Even if the data contained in a data set is stored in random order, a linear search still works as expected. This is because a linear search makes no assumption on the arrangement of the data. It simply examines every item in a data set until it finds the desired item. The main disadvantage of a linear search is its suitability for only small data sets. Remember, a linear search examines all items in a set until it finds the item. In the best case, this happens when the first item examined by a linear search is the item. In the worst case, the search terminates when the last item is examined. In this situation, the search examines every item in the data set. For a vector or array that contains several million elements, this could take a considerable amount of time, especially if the search is repeated many times. On average, a linear search examines half the items in a data set. The STL find function performs a linear search on a container. This function accepts three arguments. The first two arguments are iterators that specify a range to search. The third argument is the value that the function attempts to find. This function returns an iterator to the first position that contains the value sought. If the search is unsuccessful, the find function returns an iterator equal to the second iterator. An example usage of the find function appears in find.cpp. This program populates a vector with the first twenty-five Fibonacci numbers. It then allows the user to enter a number and reports whether or not the number is one of those Fibonacci numbers. Binary SearchWe 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… Given the vector pictured in Figure 1, we can use a binary search to find the element that contains the value 9. …Basic Sorting Algorithms · Sorting Overview · Selection Sort Sorting OverviewBecause professional programmers rarely use basic sorting algorithms, we examine only one algorithm in this page. In page 4.1.3 Fast Sorting…Selection SortFigure 1 An unsorted array Figure 1 contains an unsorted array. Since this array contains eight… Figure 2 The first passBinary поискРассмотрим пример, как он искал бы элемент в следующем векторе. Рисунок 1 Вектор, содержащий девять элементов Найти элемент, который содержит значение 9. Все двоичные поиски начинаются, с исследования элемента находящегося…Основные алгоритмы сортировки Краткий обзорТак уж складывается, профессиональные программисты редко используют основные алгоритмы сортировки, поэтому мы в настоящем курсе рассмотрим только…Selection Sort (Вид выбора)Рисунок 1 Несортированный массив Рассмотрим несортированный массив, который содержит восемь элементов, поэтому selection sort должен будет сделать…Быстро сортирующие алгоритмы Основные и быстрые алгоритмы сортировки Существует ряд алгоритмов сортировки общего назначения, которые обычно выигрывают у основных алгоритмов которые мы рассмотрели в п. 4.1.2. Эти "быстрые" алгоритмы сортировки включают сортировку с объединением, quicksort, и Shellsort. Так как quicksort, возможно, наиболее широко распространенный из алгоритмов сортировки общего назначения, мы исследуем его здесь подробно. Quicksort АлгоритмQuicksort алгоритм может быть получен в следующих четырех основных шагах. Представленные в контексте сортировки массива, эти шаги следующие. … Рассмотрим решение задачи на примере. Обратимся к рис. 1. Рисунок 1 Несортированный массивРеализацияБолее усовершенствованная quicksort реализация приведена в учебнике Вайс на странице 347. Реализация Вайса использует свою стратегию разделения и…Использование функции сортировки STLЛистинг 2 использует несколько других функций то объяснение ордера. Во-первых, функция STL generate_n используется в Перечислении 2, чтобы… вид функция может работать только на контейнерах, которые обеспечивают… В дополнение к сортировке STL обеспечивает возможность для перестановка содержание контейнера. Перестановка,…Использование Хэш-таблицы Краткий обзор Хэш-таблицКонцептуально, ассоциативные структуры данных хранят данные в парах ключ/значение. Это означает, что для каждого сохраненного значения, есть… Карты хеша и наборы хеша являются двумя различными типами хэш-таблиц. Карты…Хеш-функцииРисунок 1 Демонстрационная хеш-функция Отображение ключей к индексам демонстрируется в рисунке 1. Здесь хеш-функция… Рисунок 3 Демонстрационная хэш-таблицаРеализация Хэш-таблицы· hashmap.h - объявление класса HashMap · hashmap.cpp - определение класса HashMap Тип возврата поиск функция членства класса HashMap класс STL, с которым мы еще не встретились. Функция поиск…Fast Sorting Algorithms Basic and Fast Sorting Algorithms There exists a set of general-purpose sorting algorithms that typically outperform the basic algorithms we examined in 4.1.2 Basic Sorting Algorithms. These "fast" sorting algorithms include mergesort, quicksort, and Shellsort. Since quicksort is perhaps the most widely used of the general-purpose sorting algorithms, we examine it here in detail. Chapter 9 of the Weiss textbook discusses and presents implementations of mergesort and Shellsort. Quicksort The AlgorithmThe quicksort algorithm can be summarized in four basic steps. Presented in the context of sorting an array, these steps are as follows. If… Stepping through an example illustrates how these four steps sort a set of… Figure 1 An unsorted arrayAn ImplementationA more advanced quicksort implementation appears on page 347 of the Weiss textbook. The Weiss implementation uses a different pivot and partition…Using the STL Sorting FunctionsListing 2 uses a few other functions that warrant explanation. First, the STL function generate_n is used in Listing 2 to populate a vector with… The sort function can operate only on containers that provide random access… In addition to sorting, the STL provides the ability to shuffle the contents of a container. Shuffling, the opposite…Using Hash Tables · Overview of Hash Tables · Hash Functions · Memoizing: An Application of Hash Tables · A Hash Table Implementation Overview of Hash TablesA hash table is a type of map. Maps are associative structures. Conceptually, associative data structures store data in key-value pairs. This … Hash maps and hash sets are two different types of hash tables. Hash maps are…Hash FunctionsFigure 1 A sample hash function A mapping of keys to indexes is demonstrated in Figure 1. In this figure, the… Figure 3 A sample hash tableA Hash Table Implementation· hashmap.h - declaration of class HashMap · hashmap.cpp - definition of class HashMap The return type of the search member function of class HashMap is an STL class that we have not yet encountered.…– Конец работы – Используемые теги: Unit, Sorting, Searching, and, Complexity, Sorting, and, Searching, Complexity, Assessments, Multiple-Choice, Quiz0.139 Если Вам нужно дополнительный материал на эту тему, или Вы не нашли то, что искали, рекомендуем воспользоваться поиском по нашей базе работ: Unit 4. Sorting, Searching, and Complexity · 4.1 Sorting and Searching · 4.2 Complexity Assessments · Multiple-Choice Quiz Что будем делать с полученным материалом:Если этот материал оказался полезным для Вас, Вы можете сохранить его на свою страничку в социальных сетях:
Хотите получать на электронную почту самые свежие новости?Подпишитесь на Нашу рассылку
Наша политика приватности обеспечивает 100% безопасность и анонимность Ваших E-Mail
Реклама |
Новости и инфо для студентов