Created
September 14, 2021 06:08
-
-
Save maqbull/106be68f0dc7d9a7baa2329404d52bb0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Merge Sort | |
1. Declare left and right variable , where left = 0 , right = n-1. | |
2. find mid , which is left+right/2 | |
3. Call recursively mergeSort on (left,mid) and (mid+1,rear) | |
4. 3rd step will continue till left<right. | |
5. Then we will call merge on the 2 subproblems. | |
*/ | |
#include <bits/stdc++.h> | |
#include<iostream> | |
using namespace std; | |
void merge(int arr[], int left, int mid, int right) { | |
int len1 = mid - left + 1; | |
int len2 = right - mid; | |
int leftArr[len1]; | |
int rightArr[len2]; | |
for (int i = 0; i < len1; i++) | |
leftArr[i] = arr[left + i]; | |
for (int j = 0; j < len2; j++) | |
rightArr[j] = arr[mid + 1 + j]; | |
int i, j, k; | |
i = 0; | |
j = 0; | |
k = left; | |
while (i < len1 && j < len2) { | |
if (leftArr[i] <= rightArr[j]) { | |
arr[k] = leftArr[i]; | |
i++; | |
} else { | |
arr[k] = rightArr[j]; | |
j++; | |
} | |
k++; | |
} | |
while (i < len1) { | |
arr[k] = leftArr[i]; | |
i++; | |
k++; | |
} | |
while (j < len2) { | |
arr[k] = rightArr[j]; | |
j++; | |
k++; | |
} | |
} | |
void algorithm(int arr[],int left,int right){ | |
if (left < right) { | |
int mid = left + (right-left)/2; | |
algorithm(arr, left, mid); | |
algorithm(arr, mid + 1, right); | |
merge(arr, left, mid, right); | |
} | |
} | |
int main() { | |
int arr[] = {83,1,45,95,45,52,11,47,0,45,67,82}; | |
int n = sizeof(arr)/sizeof(arr[0]); | |
int left = 0; | |
int right = n-1; | |
algorithm(arr,left,right); | |
for(int n : arr) | |
cout<<n<<" "; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment