-
Notifications
You must be signed in to change notification settings - Fork 256
/
12 RecursiveMergeSort.cpp
64 lines (54 loc) · 1.31 KB
/
12 RecursiveMergeSort.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
#include <iostream>
using namespace std;
template <class T>
void Print(T& vec, int n, string s){
cout << s << ": [" << flush;
for (int i=0; i<n; i++){
cout << vec[i] << flush;
if (i < n-1){
cout << ", " << flush;
}
}
cout << "]" << endl;
}
void Merge(int A[], int low, int mid, int high){
int i = low;
int j = mid+1;
int k = low;
int B[high+1];
while (i <= mid && j <= high){
if (A[i] < A[j]){
B[k++] = A[i++];
} else {
B[k++] = A[j++];
}
}
while (i <= mid){
B[k++] = A[i++];
}
while (j <= high){
B[k++] = A[j++];
}
for (int i=low; i<=high; i++){
A[i] = B[i];
}
}
void RecursiveMergeSort(int A[], int low, int high){
if (low < high){
// Calculate mid point
int mid = low + (high-low)/2;
// Sort sub-lists
RecursiveMergeSort(A, low, mid);
RecursiveMergeSort(A, mid+1, high);
// Merge sorted sub-lists
Merge(A, low, mid, high);
}
}
int main() {
int A[] = {2, 5, 8, 12, 3, 6, 7, 10};
int n = sizeof(A)/sizeof(A[0]);
Print(A, n, "\t\tA");
RecursiveMergeSort(A, 0, n-1);
Print(A, n, " Sorted A");
return 0;
}