-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickSort.h
110 lines (90 loc) · 2.71 KB
/
quickSort.h
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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//CHANGE TO USE A VECTOR
//Splitting the array from the pivot
int partition(vector<int>& arr, int start, int end)
{
//create a pivot with the start value
int pivot = arr[start];
int count = 0;
for (int i = start + 1; i <= end; i++) {
if (arr[i] <= pivot)
count++;
}
//Giving pivot element its correct position
int pivotIndex = start + count;
swap(arr[pivotIndex], arr[start]);
//Sorting left and right parts of the pivot element
int leftSide = start;
int rightSide = end;
while (leftSide < pivotIndex && rightSide > pivotIndex) {
while (arr[leftSide] <= pivot) {
leftSide++;
}
while (arr[rightSide] > pivot) {
rightSide--;
}
if (leftSide < pivotIndex && rightSide > pivotIndex) {
swap(arr[leftSide++], arr[rightSide--]);
}
}
return pivotIndex;
}
//modified to take in pair vector
int partition(vector<pair<string,int>>& arr, int start, int end)
{
//create a pivot with the start value
int pivot = arr[start].second;
int count = 0;
for (int i = start + 1; i <= end; i++) {
if (arr[i].second <= pivot)
count++;
}
//Giving pivot element its correct position
int pivotIndex = start + count;
swap(arr[pivotIndex], arr[start]);
//Sorting left and right parts of the pivot element
int leftSide = start;
int rightSide = end;
while (leftSide < pivotIndex && rightSide > pivotIndex) {
while (arr[leftSide].second <= pivot) {
leftSide++;
}
while (arr[rightSide].second > pivot) {
rightSide--;
}
if (leftSide < pivotIndex && rightSide > pivotIndex) {
swap(arr[leftSide++], arr[rightSide--]);
}
}
return pivotIndex;
}
void quickSort(vector<int>& arr, int start, int end)
{
//Checks if the sort is valid to be able to sort
if (start >= end){
return;
}
//Partitioning the array
int p = partition(arr, start, end);
//Sorting the left part
quickSort(arr, start, p - 1);
//Sorting the right part
quickSort(arr, p + 1, end);
}
//modified to take in pair vector
void quickSort(vector<pair<string,int>>& arr, int start, int end)
{
//Checks if the sort is valid to be able to sort
if (start >= end){
return;
}
//Partitioning the array
int p = partition(arr, start, end);
//Sorting the left part
quickSort(arr, start, p - 1);
//Sorting the right part
quickSort(arr, p + 1, end);
}