#include<iostream>
using namespace std;
int partition(int arr[],int first,int last,int pivot)
{
int tmparr[100];
int left=first,right=last;
for(int i=first;i<=last;i++)
{
if(arr[i]<pivot)
tmparr[left++]=arr[i];
else if(arr[i]>pivot)
tmparr[right--]=arr[i];
}
//for the case when pivot is duplicated
for(int i=left;i<=right;i++)
tmparr[i]=pivot;
for(int i=first;i<=last;i++)
arr[i]=tmparr[i];
return left;
}
void quicksort(int arr[],int first,int last)
{
if(first<last)
{
int pivotindex = partition(arr,first,last,arr[first]);
quicksort(arr,first,pivotindex-1);
quicksort(arr,pivotindex+1,last);
}
}
int main()
{
int arr[6]={6,6,9,5,3,7};
int n=6;
quicksort(arr,0,n-1);
for(int i=0;i<n;i++)
cout<<arr[i];
}
How do I avoid the copying to
tmparr
?How does the current method of copying to
tmparr
and back affect my time efficiency as opposed to an in-place swap?Am I missing anything in this code? It looks much simpler than implementations I could find online.