Coders Packet

MERGE SORT in C++

By mahima mahendru

This C++ code takes the input array from the user and sort it using the merge sorting algorithm and gives the final array sorted in ascending order.

C++ IMPLEMENTATION:

#include 
#include 
#include<bits/stdc++.h>
# define ll long long 
# define endl "\n"
using namespace std;

//PRINT FUNCTION 
void print(vectorb,int n)
 {
    for(int i=0;i<n;i++)
        cout<<"  "<<b[i]<<"  ";
        cout<<endl<<endl;
 }
 
//MERGE FUNCTION

void merge(vector&a,int low ,int high)
{
    int mid=(high+low)/2;
    int i=0,j=0,k=low;
    int p=mid-low+1;
    int q=high-mid;
        vectorb(a.size());
    while(i

a[j+mid+1]) { b[k++]=a[j+mid+1]; j++; } else{ b[k++]=a[i+low]; b[k++]=a[j+mid+1]; i++;j++; } } while(i<p) { b[k++]=a[i+low]; i++; } while(j<q) { b[k++]=a[j+mid+1]; j++; } for(int i=low;i<=high;i++) a[i]=b[i]; } //MERGE SORT void merge_sort(vector&a,int low,int high) { if(low>=high)return ; int mid=(high+low)/2; // mid value merge_sort(a,low,mid); //mergesort for first half merge_sort(a,mid+1,high); //mergersort for second half merge(a,low,high); //merge the two halves print(a,a.size()); //print the modified array } int main() { cout<<"ENTER SIZE OF AARAY:\n"; int n; cin>>n; //enter size of array vectora(n); cout<<"ENTER ARRAY ELEMENTS\n"; for(int i=0;i<n;i++) cin>>a[i]; //input array //call the merge_sort function with low=0,high=n-1 merge_sort(a,0,n-1); //print the resultant sorted array cout<<"\nFINAL ARRAY SORTED IN ASCENDING ORDER:\n"; print(a,n); }

 INPUT:

input

OUTPUT:

output

Software Requirements:

Any C++ IDE like code blocks, codelite, etc

Code functionality:

1. Takes the input array size and elements from the user.

2. Gives step by step changes in the array.

3. Gives the final sorted array as the final output to the code.

4. Exit.

Procedure:

1. After the software is installed and the zip file is downloaded, locate the path of the installed C++ IDE folder and bin folder in it.

2. Then copy the .cpp file from the extracted folder and paste it into the bin folder.

3. Open the  C++  IDE, then open the .cpp file in it.

4. Run the code.

Download Complete Code

Comments

No comments yet