|
0 / 0 / 0
Регистрация: 03.11.2016
Сообщений: 18
|
|||||||||||
Quick sort using vectors04.11.2016, 16:21. Показов 3050. Ответов 10
Метки нет (Все метки)
Now that you have learned about three sorting algorithms with quadratic time complexity (Bubble, (./selection) and Insertion sorts) you should be curious, whether it is possible to perform the task significantly faster.
The problem is that if these algorithms solrt 10000 elements in a second, then they will sort 100 times more elements (one million) in about 100*100 longer time, i.e. several hours! Luckily there really are other approaches. One of them is a Quick-sort. It uses quite simple idea and allows to sort with time complexity of O(N*log(N)) which increases almost proportional to simple N rather than N*N as with simpler methods! Algorithm Suggest we have an array of numbers: 5 3 8 1 4 7 2 9 6 Let us choose some element - call it pivot and try to reorder others in such a way that ones which are lesser than pivot will be put before it while others, which are greater, will take place behind it. For example if pivot is 5 then we want something like this: 2 3 4 1 5 7 8 9 6 Now we can say that array is partially sorting - it have two unordered parts, but these parts are ordered in relation to each other. We need not move elements between them any more - only inside them. Now let us regard this array like composition of pivot and two subarrays: [2 3 4 1] 5 [7 8 9 6] Obviously we can apply the same strategy to each of sub-parts, and proceed until subarrays will decrease to the size of 1. It is convenient to use recursive function for such algorithm:
Partitioning The only tricky moment is how to perform "partitioning" - i.e. choosing pivot and reordering elements to the sides of it. Lazy implementations, especially in functional programming languages, may create two new sub-arrays and filter elements into them - however it is not "honest" since proper quicksort could be done "in-place". Here is one of the approaches, based on moving large elements to the rightmost end and small elements to the leftmost end step by step: Pivot is initially copied to temporary variable to provide one "empty" cell and is returned to array only when the pass is over. Empty space is initially placed on the left side of array. We maintain two pointers to the segment still not processed - left lt and right rt; the algorithm moves lt and rt towards each other leaving partitioned elements outside. When the empty space is on the left, we compare elements pointed by other end rt (decreasing it in loop) with pivot, until we find one which is less (and so it should not be on the right side); then this element is swapped with the "empty" space. Now (when empty space is on the right) we compare elements pointed by lt (increasing it at each step) until we find the element which is greater than pivot and should be swapped with empty space on the right. So we continue steps 4 and 5 until lt and rt meet - then we restore pivot to this point (which is "empty"). Here is the pseudocode:
Problem statement Please implement the described algorithm and run it on a sample array. For each call of quicksort please output its left and right parameters. Input data will contain N - the size of array - in the first line. Next line will contain the array itself (all elements will be different). Answer should contain left-right ranges for each call of the recursive function in order. Separate values of each pair with a dash, while pairs itself should be separated with spaces. Example: input data: 10 38 23 9 19 113 5 42 85 71 112 answer: 0-9 0-3 1-3 1-2 5-9 5-8 5-7
0
|
|||||||||||
| 04.11.2016, 16:21 | |
|
Ответы с готовыми решениями:
10
Quick sort c++ Сортировка Quick Sort Реализация алгоритма Quick sort |
|
Модератор
|
|
| 04.11.2016, 18:08 | |
|
dinbo, how it's connected to C++? Do you need translate this code from PureBasic to C++? Or code you have written is just for example and language doesn't matter? What do you really need? C++ implementation?
0
|
|
|
0 / 0 / 0
Регистрация: 03.11.2016
Сообщений: 18
|
|
| 04.11.2016, 18:16 [ТС] | |
|
it is just example of code, you have to convert to c++, i don't know how it work. can you help me ? to write with vector is necessary
0
|
|
|
Модератор
|
|
| 04.11.2016, 18:35 | |
|
There are a lot of examples here at forum. Just try to search with these keywords:
. пузырьковая сортировка. сортировка пузырьком. bubble sort. сортировка вставками. insertion sort. сортировка выбором. selection sort. Use search tool this way:
1
|
|
|
Комп_Оратор)
|
||||||
| 04.11.2016, 20:54 | ||||||
|
Гость:
-Начелдахи недурнасы... Левый слуга: -Пашли баши Правый слуга: -Пашли баши.... Уходят. Граф Лудовико: -Какой занятный язык! Если бы я знал Паскаль мог бы сказать что-то более определённое. На плюсах это может выглядеть так:
0
|
||||||
|
0 / 0 / 0
Регистрация: 03.11.2016
Сообщений: 18
|
|
| 04.11.2016, 21:02 [ТС] | |
|
IGPIGP, а сможешь решить через вектора?
0
|
|
|
Комп_Оратор)
|
||
| 04.11.2016, 21:07 | ||
|
dinbo, Вам задача, - посидите часок и сделайте на векторе. Там практически ничего делать не придётся. Но если не знаете, то это "ничего" потребует некоторых усилий.
0
|
||
|
0 / 0 / 0
Регистрация: 03.11.2016
Сообщений: 18
|
|
| 04.11.2016, 22:59 [ТС] | |
|
IGPIGP, реши, пожалуйста, через вектор
0
|
|
|
Комп_Оратор)
|
||
| 05.11.2016, 00:00 | ||
|
Объясните как дошли до такой жизни, что не можете набрать простой код? Истории про пальцы прижатые дверью в маршрутке и пр. ужасы не нужно.
0
|
||
| 05.11.2016, 10:17 | |
|
Не по теме: Весело тут у вас :D
0
|
|
|
Комп_Оратор)
|
||||||||
| 05.11.2016, 13:13 | ||||||||
|
Не по теме:
Клянусь, если ТС расскажет о слабых местах алгоритмов Шелла и быстой сортировки, я выложу перегрузку для векторов. :) Добавлено через 2 часа 48 минут dinbo, я тут порезвился слегка, но ведь не знал же, что Вы девушка. Пока в соседней теме не вычитал. ![]() Нежелание перевести суть топика на русский (хотя бы в нескольких фразах) и потом вопрос Кликните здесь для просмотра всего текста
и всё же непонятно. Класс это же не аудитория... Вы в школе учитесь?
0
|
||||||||
| 05.11.2016, 13:13 | |
|
Помогаю со студенческими работами здесь
11
Quick sort, не понятно некоторые моменты.
Метод сортировки quick sort ведомость абитуриентов Написать функцию Quick Sort для массива с 2000 элементов Быстрая Сортировка quick-sort (ошибка в 40 строке) как исправить? Искать еще темы с ответами Или воспользуйтесь поиском по форуму: |
|
Новые блоги и статьи
|
|||
|
Первый деплой
lagorue 16.01.2026
Не спеша развернул своё 1ое приложение в kubernetes.
А дальше мне интересно создать 1фронтэнд приложения и 2 бэкэнд приложения
развернуть 2 деплоя в кубере получится 2 сервиса и что-бы они. . .
|
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ *
Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам
Кирхгофа, решает её и находит токи на L и напряжения на C в установ. режимах до и. . .
|
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым.
Но восстановить их можно так.
Для этого понадобится консольная утилита. . .
|
Изучаю kubernetes
lagorue 13.01.2026
А пригодятся-ли мне знания kubernetes в России?
|
|
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
|
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11
— это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
|
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11
Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
|
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
|