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

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

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 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.
Readings:
  • Required:
    • Weiss, chapter 9 and 20.
or
    • Carrano, section 9.2.
Remark: Remember that this book supplements the course's online material. You will be asked questions based on this material.
  • Required: Schildt, chapters 33 through 37.
Remark:Remember that this book serves as a general reference to the C++ language, not a course textbook. Therefore, you should browse through the assigned sections in order to get a sense of what they have to offer and where and how they treat important topics. Do not study the sections assigned in this book as you would assignments from a textbook: your goal here should be familiarity, not mastery.

 

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.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: // Finding an element in a vector using linear search template <typename T> int linear_search(const vector<T>& v, const T& item) {   for (int i = 0; i < v.size(); i++) { if (v[i] == item) { return i; // item found } } return -1; // item not found }
Listing 1Finding an element in a vector using a linear search

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 Search

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… 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 Overview

Because professional programmers rarely use basic sorting algorithms, we examine only one algorithm in this page. In page 4.1.3 Fast Sorting…

Selection Sort

Figure 1 An unsorted array Figure 1 contains an unsorted array. Since this array contains eight… Figure 2 The first pass

Binary поиск

Рассмотрим пример, как он искал бы элемент в следующем векторе. Рисунок 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 Algorithm

The 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 array

An Implementation

A 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 Functions

Listing 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 Tables

A 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 Functions

Figure 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 table

A 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

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

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

Еще рефераты, курсовые, дипломные работы на эту тему:

The Algorithm of a Start and the Development of International Conflicts and Possible Ways of Their Solution
Every dayin world news reports we can see many examples of international conflicts.Ulster, Kosovo, Chechnya, Palestine, Macedonian - these… Whatis it? What are the reasons for it? How we can stop it if we can ? The… I also used the book by A. B. Krylov Separatism Moscow 1990 . And, of course, TV reports gave me a lot of information…

SYSTEMS OF TECHNOLOGIES AND THEIR ROLE IN SCIENTIFIC AND TECHNICAL PROGRESS.
SYSTEMS OF TECHNOLOGIES AND... THEIR ROLE IN SCIENTIFIC AND TECHNICAL... LECTURE...

Part III CUSTOMS Unit VIII CUSTOMS TARIFFS, TAXES AND DUTIES
Unit VIII CUSTOMS TARIFFS TAXES AND DUTIES... EPISODE Customs Tariffs in Russia In... Vocabulary Notes on the Text...

Россия и независимые государства (перевод из "Economic and Post-Soviet Economic Structure and Performance")
Говоря об этих начинаниях, важно знать и о действительности. Хотя новая эра наступила в январе 1992 года, очевидно, что отвержение старых порядков… Произошедший в результате распад, привел к неизбежному спаду производства… Рассматривая эту проблему с другой стороны, можно сказать, что всегда было трудно оценивать влияние советской системы…

The Comparative Analisis Of The History Of The Computer Science And The Computer Engineering In The USA And Ukraine
It is not proposed to discuss here the origins and significance of the stored program. Nor I wish to deal with the related problem of whether the… But the first stored-program machine to be put into regular operation was… Additionally, in the case of Aiken, it is significant that there is a current computer technology that does not…

Epistemology and methdology: main trends and ends. (Эпистемология и Методология)
Epistemology is one of the main branches of philosophy its subject matter concerns the nature, origin, scope, and limits of human knowledge. The name is derived from the Greek terms episteme knowledge and logos theory,… It therefore sets the standards for the validation of all knowledge it is the fundamental arbiter of cognitive method.…

Phoneme as many-sided dialectic unity of language. Types of allophones. Distinctive and irrelevant features of the phoneme
Лекции по теоретической фонетике Примерные вопросы для контроля знаний... Phonetics as a branch of linguistics Phonetics and other disciplines... Branches of phonetics...

TRAFFIC ALERT AND COLLISION AVOIDANCE SYSTEM
TRAFFIC ALERT AND COLLISION AVOIDANCE SYSTEM General TCAS sends interrogation signals to nearby... TCAS GENERAL... TCAS COMPONENT LOCATION General Description TCAS directional...

Организация библиотек. Стандартные библиотечные модули и модули пользователя. Структура Unit.
Организация библиотек... Стандартные библиотечные модули и модули пользователя... Структура Unit...

Short Happy Life of the Brown Oxford and Other Stories
На сайте allrefs.net читайте: "Short Happy Life of the Brown Oxford and Other Stories"

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