-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesort.cpp
81 lines (68 loc) · 2.55 KB
/
mergesort.cpp
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
// Merge Sort
//
// Author: Rob Gysel
// ECS60, UC Davis
// Adapted from: Lysecky & Vahid "Data Structures Essentials", zyBooks
#include "mergesort.h"
int MergeSortCompares=0;
int MergeSortMemaccess=0;
void MergeSort(std::vector<int>* numbers) {
MergeSortRecurse(numbers, 0, numbers->size() - 1);
}
void MergeSortRecurse(std::vector<int>* numbers, int i, int k) {
int j = 0;
if (i < k) {
j = (i + k) / 2; // Find the midpoint in the partition
// Recursively sort left and right partitions
MergeSortRecurse(numbers, i, j);
MergeSortRecurse(numbers, j + 1, k);
// Merge left and right partition in sorted order
Merge(numbers, i, j, k);
}
}
void Merge(std::vector<int>* numbers, int i, int j, int k) {
int mergedSize = k - i + 1; // Size of merged partition
int mergePos = 0; // Position to insert merged number
int leftPos = 0; // Position of elements in left partition
int rightPos = 0; // Position of elements in right partition
std::vector<int> mergedNumbers;
mergedNumbers.resize(mergedSize); // Dynamically allocates temporary array
// for merged numbers
leftPos = i; // Initialize left partition position
rightPos = j + 1; // Initialize right partition position
// Add smallest element from left or right partition to merged numbers
while (leftPos <= j && rightPos <= k) {
MergeSortCompares+=1;
MergeSortMemaccess+=2;
if ((*numbers)[leftPos] < (*numbers)[rightPos]) {
mergedNumbers[mergePos] = (*numbers)[leftPos];
MergeSortMemaccess+=1;
++leftPos;
}
else {
mergedNumbers[mergePos] = (*numbers)[rightPos];
MergeSortMemaccess+=1;
++rightPos;
}
++mergePos;
}
// If left partition is not empty, add remaining elements to merged numbers
while (leftPos <= j) {
mergedNumbers[mergePos] = (*numbers)[leftPos];
MergeSortMemaccess+=1;
++leftPos;
++mergePos;
}
// If right partition is not empty, add remaining elements to merged numbers
while (rightPos <= k) {
mergedNumbers[mergePos] = (*numbers)[rightPos];
MergeSortMemaccess+=1;
++rightPos;
++mergePos;
}
// Copy merge number back to numbers
for (mergePos = 0; mergePos < mergedSize; ++mergePos) {
(*numbers)[i + mergePos] = mergedNumbers[mergePos];
MergeSortMemaccess+=1;
}
}