I tried with iterative way and chose pivot element as the last element of the array. I executed it on Hacker Earth which raised the sigsegv error where the array size ranged from 1 to 10^6 and array element size from 1 to 10^9. When I tried on merge sort, it did so efficiently, it didn't even raise fault. How did that happen? Following is the code that was implemented.
// An iterative implementation of quick sort /* working*/
#include <iostream>
using namespace std;
void swap ( long int &a, long int &b )
{
long int t = a;
a = b;
b = t;
}
int partition (int arr[],long int l,long int h)
{
long int x = arr[h];
long int i = l;
long int j=h-1;
while(i<j){
if(arr[i]<x){
i++;
}
if(arr[j]>x){
j--;
continue;
}
if(arr[i]>x&&arr[j]<x){
swap(arr[i],arr[j]);
i++;
j--;
}
}
swap(arr[i],arr[h]);
return i;
}
void quickSortIterative (int arr[], int l, long int h)
{
int stack[2];
int top = -1;
stack[ ++top ] = l;
stack[ ++top ] = h;
while ( top >= 0 )
{
h = stack[ top-- ];
l = stack[ top-- ];
long int p = partition( arr, l, h );
if ( p-1 > l )
{
stack[ ++top ] = l;
stack[ ++top ] = p - 1;
}
if ( p+1 < h )
{
stack[ ++top ] = p+1;
stack[ ++top ] = h;
}
}
}
int main()
{
long int N;
cin>>N;
long int i,j;
int arr[N];
for(i=0;i<N;i++){
cin>>arr[i];
}
quickSortIterative( arr, 0, N - 1 );
for ( i = 0; i < N; ++i ){
cout<<arr[i]<<" ";
}
return 0;
}