-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
53 lines (46 loc) · 1.16 KB
/
MergeSort.cpp
File metadata and controls
53 lines (46 loc) · 1.16 KB
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
#include <iostream>
#include "Usefull.h"
#include "MergeSort.h"
void MergeSort(int array[], int arraySize) {
// Recursive end
if (arraySize == 1) {
return;
}
// Recursive call
// Divide the array in two parts until arraySize = 2
int arraySizeA = arraySize/2;
int arraySizeB = arraySize - arraySizeA;
int* arrayA = array;
int* arrayB = array + arraySizeA;
MergeSort(arrayA, arraySizeA);
MergeSort(arrayB, arraySizeB);
int a = 0;
int b = 0;
int t = 0;
int arrayTemp[arraySize]; // Always after the recursive call
while (a < arraySizeA && b < arraySizeB) {
if (arrayA[a] <= arrayB[b]) {
arrayTemp[t] = arrayA[a];
a++;
} else {
arrayTemp[t] = arrayB[b];
b++;
}
t++;
}
// Copy the remaining elements
while (a < arraySizeA) {
arrayTemp[t] = arrayA[a];
a++;
t++;
}
while (b < arraySizeB) {
arrayTemp[t] = arrayB[b];
b++;
t++;
}
// Copy the temp array to the original
for (int i = 0; i < arraySize; i++) {
array[i] = arrayTemp[i];
}
}