|
0 / 0 / 0
Регистрация: 03.11.2016
Сообщений: 18
|
|||||||||||
Quick sort using vectors04.11.2016, 16:21. Показов 3034. Ответов 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 строке) как исправить? Искать еще темы с ответами Или воспользуйтесь поиском по форуму: |
|
Новые блоги и статьи
|
||||
|
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта
Симптом:
После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
|
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
|
Новый ноутбук
volvo 07.12.2025
Всем привет.
По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне:
Ryzen 5 7533HS
64 Gb DDR5
1Tb NVMe
16" Full HD Display
Win11 Pro
|
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
|
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
|
|
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов
На странице:
https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/
нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
|
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов.
. . .
|
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
|
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
|
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут.
В век Веб все очень привыкли к дизайну Single-Page-Application .
Быстренько разберем подход "на фреймах".
Мы делаем одну. . .
|