Wednesday, July 8, 2020

Merge Sort

//code by anewbieprogrammer

#include<iostream>
using namespace std;

void merge(int arr[], int s, int e, int mid){
int temp[100];
int i = s;
int k = s;
int j = mid + 1;
while(i <= mid && j <= e){
if(arr[i] <= arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while(i <= mid){
temp[k++] = arr[i++];
}
while(j <= e){
temp[k++] = arr[j++];
}
for(int i = s; i <= e; i++){
arr[i] = temp[i];
}
}
void mergeSort(int arr[], int s, int e){
if(s >= e){
return;
}
int mid = (s + e) / 2;
mergeSort(arr, s, mid);
mergeSort(arr, mid+1, e);
merge(arr, s, e, mid);
}

int main(){
int n;
cout<<"Enter count of numbers followed by numbers: ";
cin>>n;
int arr[n];
for(int i = 0; i < n; i++){
cin>>arr[i];
}
mergeSort(arr, 0, n-1);
for(int i = 0; i < n; i++){
cout<<arr[i]<<" ";
}
return 0;
}

No comments:

Post a Comment

horizontal ads