5
5
* @details This file contains the implementation of the Adaptive Merge Sort algorithm.
6
6
* The algorithm is a stable, divide-and-conquer based sorting algorithm.
7
7
*
8
+ * @tparam T Type of elements to be sorted.
8
9
* @see https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420
9
10
*/
10
11
16
17
17
18
/* *
18
19
* @brief Function to merge two halves of an array
20
+ * @tparam T Type of elements to be sorted
19
21
* @param array Vector of elements to be sorted
20
22
* @param aux Auxiliary vector used for merging
21
23
* @param low Starting index
25
27
template <typename T>
26
28
void merge (std::vector<T>& array, std::vector<T>& aux, int low, int mid, int high) {
27
29
std::copy (array.begin () + low, array.begin () + high + 1 , aux.begin () + low);
28
-
29
30
int i = low;
30
31
int j = mid + 1 ;
31
32
for (int k = low; k <= high; ++k) {
@@ -43,6 +44,7 @@ void merge(std::vector<T>& array, std::vector<T>& aux, int low, int mid, int hig
43
44
44
45
/* *
45
46
* @brief Function to recursively sort an array using Adaptive Merge Sort
47
+ * @tparam T Type of elements to be sorted
46
48
* @param array Vector of elements to be sorted
47
49
* @param aux Auxiliary vector used for merging
48
50
* @param low Starting index
@@ -51,7 +53,6 @@ void merge(std::vector<T>& array, std::vector<T>& aux, int low, int mid, int hig
51
53
template <typename T>
52
54
void sort (std::vector<T>& array, std::vector<T>& aux, int low, int high) {
53
55
if (low >= high) return ;
54
-
55
56
int mid = low + (high - low) / 2 ;
56
57
sort (array, aux, low, mid);
57
58
sort (array, aux, mid + 1 , high);
@@ -60,13 +61,13 @@ void sort(std::vector<T>& array, std::vector<T>& aux, int low, int high) {
60
61
61
62
/* *
62
63
* @brief Function to sort an array using Adaptive Merge Sort algorithm
64
+ * @tparam T Type of elements to be sorted
63
65
* @param array Vector of elements to be sorted
64
66
* @return Vector of sorted elements
65
67
*/
66
68
template <typename T>
67
69
std::vector<T> adaptiveMergeSort (std::vector<T> array) {
68
70
if (array.size () <= 1 ) return array;
69
-
70
71
std::vector<T> aux (array.size ());
71
72
sort (array, aux, 0 , array.size () - 1 );
72
73
return array;
@@ -100,6 +101,11 @@ void testAdaptiveMergeSort() {
100
101
std::vector<int > single = {42 };
101
102
std::vector<int > expectedSingle = {42 };
102
103
assert (adaptiveMergeSort (single) == expectedSingle);
104
+
105
+ // Test negative numbers
106
+ std::vector<int > negatives = {-3 , -1 , -7 , -4 , -6 , -2 , -5 };
107
+ std::vector<int > expectedNegatives = {-7 , -6 , -5 , -4 , -3 , -2 , -1 };
108
+ assert (adaptiveMergeSort (negatives) == expectedNegatives);
103
109
104
110
std::cout << " All AdaptiveMergeSort tests passed!" << std::endl;
105
111
}
0 commit comments