-
Notifications
You must be signed in to change notification settings - Fork 72
/
mergeSort.cpp
66 lines (52 loc) · 984 Bytes
/
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
#include<bits/stdc++.h>
using namespace std;
void merge(int nums[], int left, int mid, int right){
int first = mid - left + 1, last = right -mid;
int leftArr[first], rightArr[last];
for(int i=0; i<first; i++){
leftArr[i] = nums[left+i];
}
for(int i=0; i<last; i++){
rightArr[i] = nums[mid+i+1];
}
int i=0, j=0, k=left;
while(i<first && j<last){
if(leftArr[i]<=rightArr[j]){
nums[k] = leftArr[i];
i++;
}
else{
nums[k] = rightArr[j];
j++;
}
k++;
}
while(i < first) {
nums[k] = leftArr[i];
i++;
k++;
}
while (j < last) {
nums[k] = rightArr[j];
j++;
k++;
}
}
void mergeSort(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(){
int nums[5];
for(int i=0; i<5; i++){
scanf("%d", &nums[i]);
}
mergeSort(nums, 0, 4);
for(int i=0; i<5; i++){
printf("%d\t", nums[i]);
}
}