Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.73/15: Рейтинг темы: голосов - 15, средняя оценка - 4.73
0 / 0 / 0
Регистрация: 03.11.2016
Сообщений: 18

Quick sort using vectors

04.11.2016, 16:21. Показов 3073. Ответов 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:
PureBasic
1
2
3
4
5
6
7
8
9
function quicksort(array, left, right):
    pivot_pos = partition(array, left, right)
    if pivot_pos - left > 1
        quicksort(array, left, pivot_pos - 1)
    end if
    if right - pivot_pos > 1
        quicksort(array, pivot_pos + 1, right)
    end if
end fun
Here the function receives the array being sorted as an argument and also two indices specifying which range should be sorted by this call.

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:

PureBasic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function partition(array, left, right)
    lt = left
    rt = right
    dir = 'left'        #specifies at which side is currently "empty" space
    pivot = array[left]
    while lt < rt
        if dir = 'left'
            if array[rt] > pivot
                rt = rt - 1
            else
                a[lt] = a[rt]
                lt = lt + 1
                dir = 'right'
            end if
        else
            if array[lt] < pivot
                lt = lt + 1
            else
                a[rt] = a[lt]
                rt = rt - 1
                dir = 'left'
            end if
        end if
    end while
    array[lt] = pivot       #here lt = rt - both points to empty cell where pivot should return
    return lt
end fun
Examine this algorithm step by step with pencil and paper to see how it works.

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
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
04.11.2016, 16:21
Ответы с готовыми решениями:

Quick sort c++
Добрый день. Есть вопрос, как можно реализовать Quick sort с подсчётом перестановок. По условию задания у нас есть 10000 элементов. ...

Сортировка Quick Sort
Можно написать код и коментами.

Реализация алгоритма Quick sort
пожалуйсто напишите алгоритм Quick sort

10
Модератор
Эксперт CЭксперт С++
 Аватар для sourcerer
5288 / 2376 / 342
Регистрация: 20.02.2013
Сообщений: 5,773
Записей в блоге: 20
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
Модератор
Эксперт CЭксперт С++
 Аватар для sourcerer
5288 / 2376 / 342
Регистрация: 20.02.2013
Сообщений: 5,773
Записей в блоге: 20
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:
Миниатюры
Quick sort using vectors  
1
Комп_Оратор)
Эксперт по математике/физике
 Аватар для IGPIGP
9007 / 4708 / 630
Регистрация: 04.12.2011
Сообщений: 14,003
Записей в блоге: 16
04.11.2016, 20:54
Гость:
-Начелдахи недурнасы...
Левый слуга:
-Пашли баши
Правый слуга:
-Пашли баши....
Уходят.
Граф Лудовико:
-Какой занятный язык!

Если бы я знал Паскаль мог бы сказать что-то более определённое. На плюсах это может выглядеть так:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;
template<typename T>
int partition_srt(T *ar_ray, int left, int right)
{
int lt = left,
    rt = right;
enum DIR {LEFT, RIGHT};
DIR dir = LEFT;
T pivot = ar_ray[left];
 
while( lt < rt ){
    if(dir == LEFT){
        if (ar_ray[rt] > pivot){
                rt = rt - 1 ;
        }
        else{
                ar_ray[lt] = ar_ray[rt] ;
                lt = lt + 1 ;
                dir = RIGHT ;
        }
    }
    else{
        if (ar_ray[lt] < pivot){
                lt = lt + 1 ;
        }
        else{
                ar_ray[rt] = ar_ray[lt] ;
                rt = rt - 1 ;
                dir = LEFT ;
            }
    }
}
    ar_ray[lt] = pivot;       //here lt = rt - both points to empty cell where pivot should return
    return lt;
}
 
template<typename T>    
void quick_part_sort(T *ar_ray, int left, int right){
    int pivot_pos = partition_srt(ar_ray, left, right);
    if (pivot_pos - left > 1)
        quick_part_sort(ar_ray, left, pivot_pos - 1);
   
    if (right - pivot_pos > 1)
        quick_part_sort(ar_ray, pivot_pos + 1, right);
    }
 
 
int main(int argc, char* argv[])
{
    int ar[]={5, 7, 25, 43, 30, 1, 10, 15, 18, 31 };
 
for(int i=0; i<10; ++i)cout<<ar[i]<<' '; 
cout<<endl;
quick_part_sort(ar, 0, 9);
for(int i=0; i<10; ++i)cout<<ar[i]<<' '; 
cout<<endl;
system("pause");
return 0;
}
Занятная штучка.
0
0 / 0 / 0
Регистрация: 03.11.2016
Сообщений: 18
04.11.2016, 21:02  [ТС]
IGPIGP, а сможешь решить через вектора?
0
Комп_Оратор)
Эксперт по математике/физике
 Аватар для IGPIGP
9007 / 4708 / 630
Регистрация: 04.12.2011
Сообщений: 14,003
Записей в блоге: 16
04.11.2016, 21:07
Цитата Сообщение от dinbo Посмотреть сообщение
IGPIGP, а сможешь решить через вектора?
Хотите вызвать у меня азарт? - Облом. Такой вопрос, как ведро холодной воды. Я думал Вы читаете алгоритмы и вникаете. А на плюсах не получается, пока.
dinbo, Вам задача, - посидите часок и сделайте на векторе. Там практически ничего делать не придётся. Но если не знаете, то это "ничего" потребует некоторых усилий.
0
0 / 0 / 0
Регистрация: 03.11.2016
Сообщений: 18
04.11.2016, 22:59  [ТС]
IGPIGP, реши, пожалуйста, через вектор
0
Комп_Оратор)
Эксперт по математике/физике
 Аватар для IGPIGP
9007 / 4708 / 630
Регистрация: 04.12.2011
Сообщений: 14,003
Записей в блоге: 16
05.11.2016, 00:00
Цитата Сообщение от dinbo Посмотреть сообщение
IGPIGP, реши, пожалуйста, через вектор
Это не задача чтобы её решать. Этот код как материал по сортировкам со скоростью менее чем квадратичной, это же не из курса кулинарного техникума. То есть, предполагается, что обучаемый должен знать материал.
Объясните как дошли до такой жизни, что не можете набрать простой код? Истории про пальцы прижатые дверью в маршрутке и пр. ужасы не нужно.
0
05.11.2016, 10:17

Не по теме:

Весело тут у вас :D

0
Комп_Оратор)
Эксперт по математике/физике
 Аватар для IGPIGP
9007 / 4708 / 630
Регистрация: 04.12.2011
Сообщений: 14,003
Записей в блоге: 16
05.11.2016, 13:13

Не по теме:

Цитата Сообщение от Aymurat Посмотреть сообщение
Весело тут у вас
Угощайся. :)
Клянусь, если ТС расскажет о слабых местах алгоритмов Шелла и быстой сортировки, я выложу перегрузку для векторов. :)



Добавлено через 2 часа 48 минут
dinbo, я тут порезвился слегка, но ведь не знал же, что Вы девушка. Пока в соседней теме не вычитал.
Нежелание перевести суть топика на русский (хотя бы в нескольких фразах) и потом вопрос
Цитата Сообщение от dinbo Посмотреть сообщение
IGPIGP, а сможешь решить через вектора?
вызвали желание пошутить. Вот тут и для вектора перегрузка:
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
int partitition_srt(T *ar_ray, int left, int right)
{
int lt = left,
    rt = right;
enum DIR {LEFT, RIGHT};
DIR dir = LEFT;
T pivot = ar_ray[left];
 
while( lt < rt ){
    if(dir == LEFT){
        if (ar_ray[rt] > pivot){
                rt = rt - 1 ;
        }
        else{
                ar_ray[lt] = ar_ray[rt] ;
                lt = lt + 1 ;
                dir = RIGHT ;
        }
    }
    else{
        if (ar_ray[lt] < pivot){
                lt = lt + 1 ;
        }
        else{
                ar_ray[rt] = ar_ray[lt] ;
                rt = rt - 1 ;
                dir = LEFT ;
            }
    }
}
    ar_ray[lt] = pivot;       //here lt = rt - both points to empty cell where pivot should return
    return lt;
}
 
template<typename T>    
void quick_part_sort(T *ar_ray, int left, int right){
    int pivot_pos = partitition_srt(ar_ray, left, right);
    if (pivot_pos - left > 1)
        quick_part_sort(ar_ray, left, pivot_pos - 1);
   
    if (right - pivot_pos > 1)
        quick_part_sort(ar_ray, pivot_pos + 1, right);
    }
 
template<typename T>
int partitition_srt(vector<T> &ar_ray, int left, int right)
{
int lt = left,
    rt = right;
enum DIR {LEFT, RIGHT};
DIR dir = LEFT;
T pivot = ar_ray[left];
 
while( lt < rt ){
    if(dir == LEFT){
        if (ar_ray[rt] > pivot){
                rt = rt - 1 ;
        }
        else{
                ar_ray[lt] = ar_ray[rt] ;
                lt = lt + 1 ;
                dir = RIGHT ;
        }
    }
    else{
        if (ar_ray[lt] < pivot){
                lt = lt + 1 ;
        }
        else{
                ar_ray[rt] = ar_ray[lt] ;
                rt = rt - 1 ;
                dir = LEFT ;
            }
    }
}
    ar_ray[lt] = pivot;       //here lt = rt - both points to empty cell where pivot should return
    return lt;
}
 
template<typename T>    
void quick_part_sort(vector<T> &ar_ray, int left, int right){
    int pivot_pos = partitition_srt(ar_ray, left, right);
    if (pivot_pos - left > 1)
        quick_part_sort(ar_ray, left, pivot_pos - 1);
   
    if (right - pivot_pos > 1)
        quick_part_sort(ar_ray, pivot_pos + 1, right);
    }
 
int main(int argc, char* argv[])
{
    int ar[]={5, 7, 25, 43, 30, 1, 10, 15, 18, 31 };
 
for(int i=0; i<10; ++i)cout<<ar[i]<<' '; 
cout<<endl;
quick_part_sort(ar, 0, 9);
for(int i=0; i<10; ++i)cout<<ar[i]<<' '; 
cout<<endl<<endl;
 
int arr[]={5, 7, 25, 43, 30, 1, 10, 15, 18, 31 };
 
vector<int> vec(arr, arr+10);
for(int i=0; i<10; ++i)cout<<vec[i]<<' '; 
cout<<endl;
quick_part_sort(vec, 0, 9);
for(int i=0; i<10; ++i)cout<<vec[i]<<' '; 
cout<<endl;
 
system("pause");
return 0;
}

и всё же непонятно. Класс это же не аудитория... Вы в школе учитесь?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
05.11.2016, 13:13
Помогаю со студенческими работами здесь

Quick sort, не понятно некоторые моменты.
здравствуйте нужно реализовать quicksort Есть код с учебника по которому мы учимся, и вот не понятно некоторые моменты кода ...

Алгоритм Быстрой сортировки (Quick Sort)
Всем доброго времени суток. Реализовал Быструю Сортировку на C++. Всё работает. Только препод требует доказать, что мой алгоритм...

Метод сортировки quick sort ведомость абитуриентов
Ведомость абитуриентов, сдавших вступительные экзамены в университет, содержит: Ф.И.О. абитуриента, оценки. Определить средний балл по...

Написать функцию Quick Sort для массива с 2000 элементов
Написать функцию Quick Sort. Использовать написанную функцию для сортировки массива типа double на 2000 элементов. Нужна помощь:-|

Быстрая Сортировка quick-sort (ошибка в 40 строке) как исправить?
#include &lt;iostream&gt; #include &lt;vector&gt; using std::endl; using std::cout; using std::vector; template&lt;class T&gt; void...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
11
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru