-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0912-sort-an-array.cpp
63 lines (58 loc) · 1.95 KB
/
0912-sort-an-array.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
class Solution {
// Function to merge two sub-arrays in sorted order.
void merge(vector<int> &arr, int left, int mid, int right, vector<int> &tempArr) {
// Calculate the start and sizes of two halves.
int start1 = left;
int start2 = mid + 1;
int n1 = mid - left + 1;
int n2 = right - mid;
// Copy elements of both halves into a temporary array.
for (int i = 0; i < n1; i++) {
tempArr[start1 + i] = arr[start1 + i];
}
for (int i = 0; i < n2; i++) {
tempArr[start2 + i] = arr[start2 + i];
}
// Merge the sub-arrays 'in tempArray' back into the original array 'arr' in sorted order.
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (tempArr[start1 + i] <= tempArr[start2 + j]) {
arr[k] = tempArr[start1 + i];
i += 1;
} else {
arr[k] = tempArr[start2 + j];
j += 1;
}
k += 1;
}
// Copy remaining elements
while (i < n1) {
arr[k] = tempArr[start1 + i];
i += 1;
k += 1;
}
while (j < n2) {
arr[k] = tempArr[start2 + j];
j += 1;
k += 1;
}
}
// Recursive function to sort an array using merge sort
void mergeSort(vector<int> &arr, int left, int right, vector<int> &tempArr) {
if (left >= right) {
return;
}
int mid = (left + right) / 2;
// Sort first and second halves recursively.
mergeSort(arr, left, mid, tempArr);
mergeSort(arr, mid + 1, right, tempArr);
// Merge the sorted halves.
merge(arr, left, mid, right, tempArr);
}
public:
vector<int> sortArray(vector<int>& nums) {
vector<int> temporaryArray(nums.size());
mergeSort(nums, 0, nums.size() - 1, temporaryArray);
return nums;
}
};