merge sort easy and best program and algorithm in c++

WHY VECTOR?

The better approach over an array is the vector. This may sound bizarre to the newbies, learning c++. 
Let me ask you a question before we walk through the code. 
Let us take

                          int *arr=new int[n];
this creates n integer space holders in heap, pretty intuitive right.
Assume that we have filled up the integer space holders with some integer values and we pass this array arr to a function. 
Let the function be 
auto fun(int a[])
//what is a here, well your quick answer is it's an integer array  X---you are wrong buddy.
It is an integer pointer.It's  size depends on the architecture.
auto fun(int a[])
{int n=sizeof(a)/sizeof(a[0]);/*this gives you different answer in different computers based on the its architecture, whether it's a 16 or 32 or 64 bit*/
}
Because we are actually calculating the size of integer pointer.
sizeof(int *)/sizeof(int);
To understand this better see this post
 To avoid all these in-deliberate mistakes, I have chosen the vector collection.COOL right...


Merge Sort source code using vector collection in c++

#include<iostream>
#include<vector>
using namespace std;
class MergeSort
{
public:
void Merge(vector<int>&arr) //pass by reference to reflect the values in the array
                  {
int n=arr.size();
if(n<2)
return;  //base case
                     //recursion part
int mid=n/2;
vector<int>l;
vector<int>r;
for(int i=0;i<mid;i++)
l.push_back(arr[i]);
for(int i=0;i<(n-mid);i++)
r.push_back(arr[mid+i]);
Merge(l);
Merge(r);
MergeUtil(arr,l,r);
l.clear();//To clear the elements of the vector
r.clear();
}
void MergeUtil(vector<int>&a,vector<int>&l,vector<int>&r) //pass by reference
              {
int i,j,k;
i=j=k=0;
while(i<l.size()&&j<r.size() ){
if(l[i]<=r[j])
a[k++]=l[i++];
else
a[k++]=r[j++];
}
while(i<l.size() )
a[k++]=l[i++];
while(j<r.size() )
a[k++]=r[j++];
}
};
int main(){int n;cin>>n;
vector<int>arr;int d;
    for(int i=0;i<n;i++){
    cin>>d;
arr.push_back(d);
}
MergeSort m;
m.Merge(arr);
for(int i=0;i<arr.size();i++)
cout<<arr[i];
}

Please do see \this documentation on when to use vector

Comments

Popular posts from this blog

compiler unchecked warnings -java