Merge Sort ( Array )

PROBLEM :

Given a random set of numbers, Print them in sorted order.

Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.

Output:
Print each sorted array in a seperate line. For each array its numbers should be seperated by space.

Constraints:
1 = T = 10
1 = N = 1000
1 =A[i]<100

Example:
Input:
1
2
3 1 4 5 2

Output:
1 2 3 4 5

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#define MAX 100

void MergeSort(int [],int ,int ) ;
void SortBack(int [],int ,int ,int ,int ) ;

int main()
{
int t ;
cin>>t ;

while(t--)
{
   int no ;
   cin>>no ;
 
   int arr[no] ;
   for(int i=0;i<no;i++)
       cin>>arr[i] ;
     
   MergeSort(arr,0,no-1) ;
 
   for(int i=0;i<no;i++)
       cout<<arr[i]<<" " ;
     
   cout<<endl ;
}
return 0;
}

void MergeSort(int arr[],int start,int end)
{
    if(start<end)
    {
        int mid=(start+(end-1))/2 ;
        MergeSort(arr,start,mid) ;
        MergeSort(arr,mid+1,end) ;
        SortBack(arr,start,mid,mid+1,end) ;
    }
}

void SortBack(int arr[],int Fstart,int Fend,int Sstart,int Send)
{
    int temp[MAX]={0} ;
    int i,j,k ;
   
    i=Fstart;
    j=Sstart ;
    k=0 ;
   
    while(i<=Fend&&j<=Send)
    {
        if(arr[i]<arr[j])
            temp[k++]=arr[i++] ;
        else
            temp[k++]=arr[j++] ;
    }
   
    while(i<=Fend)
        temp[k++]=arr[i++] ;
    while(j<=Send)
        temp[k++]=arr[j++] ;
       
    for(i=0,j=Fstart;j<=Send;i++,j++)
        arr[j]=temp[i] ;
}

--------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )