-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSorting.h
126 lines (105 loc) · 2.27 KB
/
Sorting.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//
// Created by Development Environment on 4/29/19.
// Typical sorting algorithms used
//
#ifndef LAB3_1_SORTING_H
#define LAB3_1_SORTING_H
/**
*
* @tparam T
* @param p_val1
* @param p_val2
*/
template <typename T>
void swap(T *p_val1, T *p_val2)
{
if (p_val1 == nullptr) {
return;
} else {
if (p_val2 == nullptr) {
return;
}
}
T p_temp = *p_val1;
*p_val1 = *p_val2;
*p_val2 = p_temp;
}
template <typename T>
void bubbleSort(T* arr, const int leftSize, const int rightSide)
{
int i;
for (i = leftSize; rightSide - 1 > i; i++)
{
for (int j = leftSize; j < rightSide - i - 1; j++)
{
if (!(arr[j] > arr[j + 1]))
continue;
swap(&arr[j], &arr[j + 1]);
}
}
}
template <typename T>
void quicksort(T* arr, const int leftSide, const int rightSide)
{
if (arr[leftSide] <= arr[(rightSide + leftSide) / 2]) {}
else {
swap(arr[leftSide], arr[(rightSide + leftSide) / 2]);
}
if (arr[(rightSide + leftSide) / 2] <= arr[rightSide]) {}
else {
swap(arr[rightSide], arr[(rightSide + leftSide) / 2]);
}
if (arr[leftSide] <= arr[(rightSide + leftSide) / 2]) {}
else {
swap(arr[leftSide], arr[(rightSide + leftSide) / 2]);
}
// Variables
int i = leftSide,
j = rightSide;
T p_pivot = arr[(leftSide + rightSide) / 2];
while (i <= j)
{
while (arr[i] < p_pivot)
{
i++;
}
while (arr[j] > p_pivot)
{
j--;
}
if (i <= j)
{
swap(arr[i], arr[j]);
i++;
j--;
}
}
if (leftSide < j)
{
quicksort(arr, leftSide, j);
}
if (i < rightSide)
{
quicksort(arr, i, rightSide);
}
}
template <typename T>
void insertionSort(T* array, const int leftSide, const int rightSide)
{
T key;
int j;
int i;
for (i = leftSide; i < rightSide; i++)
{
key = array[i];
j = i - 1;
if (j >= leftSide) {
while (array[j] > key) {
array[j + 1] = array[j];
j = j - 1;
}
} // end while
array[j + 1] = key;
}
}
#endif //LAB3_1_SORTING_H