Merge sort algorithm and source code

 #include<iostream>
#include<conio.h>
using namespace std;

void merge(int arr[], int s, int mid, int e){
	cout<<"merge is running..."<<endl;
	int len1=mid-s+1;
	int len2= e-mid;
	int first[len1];
	int second[len2];
	

	for(int i=0; i<len1; i++){
		first[i]=arr[s+i];
	}

	for(int i=0; i<len2; i++){
		second[i]=arr[mid+1+i];
	}
	
	// now merge two sorted arrays
	
	int k=0,l=0,m=s;
	
	while(k < len1 && l < len2){
		if( first[k] < second[l] ){
			arr[m++]=first[k++];
		}
		else{
			arr[m++]=second[l++];
		}
	}
	
	while(k<len1){
		arr[m++]=first[k++];
	}

	while(l<len2){
		arr[m++]=second[l++];
	}	
	
	
}

void divide(int arr[], int s, int e, char ch){
	cout<<"Divide is running.."<<ch<<endl;
	if(s<e){
		int mid= s+(e-s)/2;
		divide(arr, s, mid, 'L');
		divide(arr, mid+1, e, 'R');
		merge(arr, s, mid, e);
	}
}

int main(){

	int arr[]={3,2,21,5,90,67,76};
	
	divide(arr, 0, 6,'M');
	
	for(int i=0; i<7; i++){
		cout<< arr[i] << "\t";
	}
		
	getch();
	return 0;
}
© 2016 - 2022, All Rights are Reserved.