Merge Sort in C++
Merge Sort in C++
#include<iostream>
using namespace std;
void merge(int *arr,int start,int mid, int end)
{
int x=start,y=mid+1,z=0,i,size=end-start+1;
int *temp=new int[size];
while(true)
{
if(x>mid || y>end)
break;
if(arr[x]<arr[y])
{
temp[z]=arr[x];
x++;
z++;
}
else
{
temp[z]=arr[y];
y++;
z++;
}
}
if(x>mid)
{
while(y<=end)
{
temp[z]=arr[y];
y++;
z++;
}
}
else
{
while(x<=mid)
{
temp[z]=arr[x];
x++;
z++;
}
}
for(i=0;i<z;i++)
{
arr[start]=temp[i];
start++;
}
delete [] temp;
}
void divided_conqure(int *arr,int start_index,int last_index)
{
if(start_index==last_index)
return;
int mid=(start_index+last_index)/2;
divided_conqure(arr,start_index,mid);
divided_conqure(arr,mid+1,last_index);
merge(arr,start_index,mid,last_index);
}
int main()
{
int arr[]= {7,8,1,2,9,5,3}; //start index of arr is 0 and end index 6.
divided_conqure(arr,0,6);
for(int i=0;i<7;i++)
cout<<arr[i]<<" ";
return 0;
}
Comments
Post a Comment