forked from monuverma1501/HactoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort_algorithem
42 lines (39 loc) · 910 Bytes
/
MergeSort_algorithem
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
#include<bits/stdc++.h>
using namespace std;
void merge(vector<int>& nums , int left , int mid , int right) {
int i = left;
int j = mid + 1;
int k = left;
int arr[right + 1];
while (i <= mid && j <= right) {
if (nums[i] < nums[j]) {
arr[k++] = nums[i++];
} else {
arr[k++] = nums[j++];
}
}
while (i <= mid) {
arr[k++] = nums[i++];
}
while (j <= right) {
arr[k++] = nums[j++];
}
for (int i = left; i <= right; i++) {
nums[i] = arr[i];
}
}
void mergesort(vector<int>& nums, int left , int right) {
if (left < right) {
int mid = (left + right) / 2;
mergesort(nums , left , mid);
mergesort(nums , mid + 1 , right);
merge(nums , left , mid , right);
}
}
int main() {
vector<int>nums = {13, 33, 43, 16, 25, 19, 23, 31, 29, 35, 10, 2, 32, 11, 47, 15, 34, 46};
mergesort(nums, 0 , nums.size() - 1);
for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << endl;
}
}