Skip to content

Instantly share code, notes, and snippets.

@TanmayChakrabarty
Last active August 26, 2019 20:46
Show Gist options
  • Save TanmayChakrabarty/ec5d95b0706ee5b5659d14631af8bcf7 to your computer and use it in GitHub Desktop.
Save TanmayChakrabarty/ec5d95b0706ee5b5659d14631af8bcf7 to your computer and use it in GitHub Desktop.
Merging Sort in C++
/*
Data Structure Lab Test
Date 16/04/2011
Programmed by Tanmay Chakrabarty
CSE.
Compatible with C++, C++14, C++17
Tested at https://www.onlinegdb.com/online_c++_compiler
*/
#include <iostream>
using namespace std;
int main(){
int first_array_size, second_array_size,i,j,k, merged_array_size;
/*
i will be used for the first array.
j will be used for the second array.
k will be used for the merged array.
*/
cout<<"PLEASE READ: No kind of input exceptions has been handled.\n";
cout<<"Don't Play with Inputs.\n";
cout<<"__________________________________________________________\n\n";
cout<<"Please enter the number of elements of the first list : ";
cin>>first_array_size;
int *first_array = new int [first_array_size];
cout<<"\nPlease enter the elements of first list in ascending order\n\n\t";
for(i=0;i<first_array_size;i++)
cin>>first_array[i];
cout<<"\nPlease enter the number of elements of the second list : ";
cin>>second_array_size;
int *second_array = new int [second_array_size];
cout<<"\nPlease enter the elements of second list in ascending order\n\n\t";
for(j=0;j<second_array_size;j++)
cin>>second_array[j];
merged_array_size=first_array_size + second_array_size;
int *merged_array=new int [merged_array_size];
j=i=k=0;
//Loop continues till we are inside of both of the arrays
while(i<first_array_size && j<second_array_size){
if(first_array[i] < second_array[j]){ //Finding the lowest
merged_array[k]=first_array[i]; //Putting it in the merged array
i++; //As value from first array has been taken, increasing i
k++; //increasing k for the next space of the merged array
}
else{
merged_array[k]=second_array[j];
j++;
k++;
}
}
if(i==first_array_size){ //it means, all values from first array has been taken
for(j=j;j<second_array_size;j++){ //Thus taking rest of the values of the second array
merged_array[k]=second_array[j];
k++;
}
}
else if(j==second_array_size){ //it means, all values from second array has been taken
for(i=i;i<first_array_size;i++){ //Thus taking rest of the values of the first array
merged_array[k]=first_array[i];
k++;
}
}
else{
//it means all the values from the two arrays has been taken and nothing to do.
}
cout<<"\n\nThe Merged array is as follows:\n\n";
for(i=0;i<merged_array_size;i++){ //Now we can print the merged array
if(i != (merged_array_size - 1))
cout<<merged_array[i]<<" , ";
else
cout<<merged_array[i]<<"\n\n";
}
//system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment