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

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

The Algorithm

The Algorithm - раздел Образование, Unit 4. Sorting, Searching, and Complexity · 4.1 Sorting and Searching · 4.2 Complexity Assessments · Multiple-Choice Quiz Quicksort Is A Fast Sorting Algorithm That Uses A Divide-And-Conquer Problem ...

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 of elements to sort, the algorithm recursively divides the array into smaller and smaller arrays. Quicksort then sorts these very small arrays and combines the results to create a sorted version of the original array. Because of its recursive nature, the quicksort implementation can be hard to understand. Before examining an implementation, we consider the idea behind 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.

  1. If the size of the array is zero or one, then return the array. This is the base case.
  2. Select an element from the array to be used as the pivot element. This is the pivot selection step.
  3. Create two new arrays. Place all the elements from the original array that are less than the pivot element into one of these sub-arrays and all the elements that are greater than the pivot element into the other sub-array. This is the partitioning step.
  4. Return the array that contains the result of the quicksorted sub-array that contains the elements less than the pivot, followed by the pivot, followed by the result of the quicksorted sub-array that contains the elements greater than the pivot. This is the recursive divide step.

Stepping through an example illustrates how these four steps sort a set of data. Consider the array presented in Figure 1.


Figure 1 An unsorted array

Since the array in Figure 1 contains more than one element, quicksort enters step two and selects a pivot element. There are many different strategies we can use to pick this pivot element. One that is simple involves choosing the middle element of the array as the pivot element. This element contains the value 33. After selecting the pivot element, quicksort partitions the remaining elements into two sub-arrays. One sub-array contains the elements of the partitioned array whose values are less than 33, and the other sub-array contains the elements whose values are greater than 33. Figure 2 illustrates this first pivot and partition step. In this figure, a circle denotes the pivot element.


Figure 2 Pivot selection and partition

The first partition creates two smaller arrays. The quicksort algorithm then recursively calls itself on these arrays. Notice that both of these arrays contain two or more elements. Therefore, the algorithm selects pivot elements for each array and partitions their remaining elements into smaller arrays. The result of this appears in Figure 3.


Figure 3 Second level partitioning

The quicksort algorithm only needs to select pivot elements and partition sub-arrays that contain more than one element. From Figure 3, we see after two partitions we are left with four sub-arrays. These arrays appear in the bottom row of the figure. Starting from the left side of the figure, the first sub-array contains only one element (the value 3). The second sub-array contains elements 12 and 21, and the third sub-array contains elements 52 and 53. The fourth sub-array contains zero elements. The empty set sign (a circle with a diagonal line through it) denotes that this sub-array contains zero elements. The quicksort algorithm does not need to pivot and partition the first and fourth arrays since they each contain less than two elements. At this point, these two sub-arrays are sorted. Since the second and third arrays each contain more than one element, there is the possibility they are not in sorted order. Quicksort must recursively pivot and partition these arrays. This is demonstrated in Figure 4.


Figure 4 After last necessary partition

The recursive nature of quicksort breaks down the original array into smaller and smaller sub-arrays. The pivoting and partitioning of these sub-arrays eventually results in the sorting of the entire array. Figure 5 depicts the sorted version of the original array from our ongoing example.


Figure 5 The sorted array

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

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

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"

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

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

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

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

Binary Search
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 larg

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

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

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

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

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
Реклама
Соответствующий теме материал
  • Похожее
  • Популярное
  • Облако тегов
  • Здесь
  • Временно
  • Пусто
Теги