Commit 1ab6f142 authored by POORVI HEBBAR's avatar POORVI HEBBAR

change implementation to merge-sort

parent 6a5d2ec6
#include<iostream> #include<iostream>
#include<vector>
#include "sorting.h" #include "sorting.h"
using namespace std; using namespace std;
vector<int> merge(vector<int> arr1, vector<int> arr2){
int n1=arr1.size(), n2=arr2.size(),count1=0,count2=0;
vector<int> mergedArray(n1+n2);
for(int i=0;i<n1+n2;i++){
if(count1>=n1){
mergedArray[i]=arr2[count2];
count2++;
}
else if(count2>=n2){
mergedArray[i]=arr1[count1];
count1++;
}
else{
if(arr1[count1]<=arr2[count2]){
mergedArray[i]=arr1[count1];
count1++;
}
else{
mergedArray[i]=arr2[count2];
count2++;
}
}
}
return mergedArray;
}
vector<int> sort_custom(vector<int> arr){ vector<int> sort_custom(vector<int> arr){
int N=arr.size(); int n=arr.size();
for(int i=0;i<N;i++) if(n==1){
for(int j=0;j<N-i-1;j++) return arr;
if(arr[j]>arr[j+1]) }
swap(arr[j],arr[j+1]); else
return arr; {
int n1=n/2;
int n2=n-n1;
vector<int> arr1(n1),arr2(n2);
for(int i=0;i<n;i++){
if(i<n1)
arr1[i]=arr[i];
else if(i<n1+n2)
arr2[i - n1]=arr[i];
}
vector<int> ans1=sort_custom(arr1);
vector<int> ans2=sort_custom(arr2);
vector<int> ans=merge(ans1,ans2);
return ans;
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment