From 95b4d7eced0e091844027615879d0c0ac9b2fa47 Mon Sep 17 00:00:00 2001 From: Tanish Agarwal Date: Sat, 7 Aug 2021 10:38:54 +0530 Subject: [PATCH] implement merge sort --- merge_sort.cpp | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 merge_sort.cpp diff --git a/merge_sort.cpp b/merge_sort.cpp new file mode 100644 index 0000000..deb9738 --- /dev/null +++ b/merge_sort.cpp @@ -0,0 +1,69 @@ +#include +using namespace std; + +void merge(vector& arr, int l, int mid, int r){ + int l1 = mid - l + 1; + int l2 = r - mid; + vector a1; + vector a2; + + for(int i = 0; i < l1; i++) { + a1.emplace_back(arr[l + i]); + } + for(int i = 0; i < l2; i++) { + a2.emplace_back(arr[mid + 1 + i]); + } + + int i = 0, j = 0, k = l; + + while(i < l1 && j < l2) { + if(a1[i] < a2[j]) { + arr[k++] = a1[i++]; + }else { + arr[k++] = a2[j++]; + } + } + + while(i < l1) { + arr[k++] = a1[i++]; + } + while(j < l2) { + arr[k++] = a2[j++]; + } +} + +void mergeSort(vector& arr, int l, int r) { + + if(l < r) { + int mid = (l + r) / 2; + mergeSort(arr, l, mid); + mergeSort(arr, mid + 1, r); + + merge(arr, l, mid, r); + } + + +} + +int main() { + int n; + cin>>n; + int count = 0; + + vector arr; + + for(int i = 0; i < n; i++) { + int x; + cin>>x; + + arr.emplace_back(x); + } + + mergeSort(arr, 0, n-1); + + for(auto it: arr) { + cout<