Quick 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 QuickSort(int [],int ,int ) ;
int FindPivot(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] ;
     
   QuickSort(arr,0,no-1) ;
 
   for(int i=0;i<no;i++)
       cout<<arr[i]<<" " ;
     
   cout<<endl ;
}
return 0;
}

void QuickSort(int arr[],int start,int end)
{
    if(start<end)
    {
    int pivot ;
    pivot=FindPivot(arr,start,end) ;
    QuickSort(arr,start,pivot-1) ;
    QuickSort(arr,pivot+1,end) ;
}
}

int FindPivot(int arr[],int start,int end)
{
int i,curr,pivot ;
pivot=arr[end] ;
curr=start ;

int temp ;
for(i=start;i<end;i++)
{
if(arr[i]<pivot)
{
temp=arr[i] ;
arr[i]=arr[curr] ;
arr[curr]=temp ;
curr++ ;
}
}
temp=arr[end] ;
arr[end]=arr[curr] ;
arr[curr]=temp ;

return curr ;
}

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

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 )