I have written this quick sort algorithm but it doesn't work properly for some reason, I need some help to find out the error.
I tried not to use built-in swap function however it didn't work out.
FindPivot function returns the median of three elements (start, half, end) of the array after swapping them so that the smallest one is at the start, the greatest at the middle and the median at the end of the array
#include <bits/stdc++.h>
using namespace std;
int pivotIdx, pivot, n;
int partitn(int* arr, int first, int last)
{
pivot = FindPivot(arr,first,last-1);
// pivot = arr[last-1];
cout << "Pivot: " << pivot << endl;
int L = first;
int R = last-2;
while(L<R)
{
while(arr[L]<=pivot)
L++;
while(arr[R]>=pivot)
R--;
swap(arr[L++],arr[R--]);
}
swap(arr[L],arr[last-1]);
return L;
}
void QuickSort(int* arr,int first,int last)
{
if(last-first < 6){
InsertionSort(arr,first,last);
}else{
pivotIdx = partitn(arr, first, last);
QuickSort(arr, first, pivotIdx);
QuickSort(arr, pivotIdx+1, last);
}
}
int main()
{
cin >> n;
int arr[100];
for(int i=0;i<n;i++)
cin>>arr[i];
QuickSort(arr,0,n);
for(int i=0;i<n;i++){
cout << arr[i] << " ";
}
return 0;
}
Input:
8
5 1 6 2 7 3 8 4
Output:
Pivot: 4
1 2 3 5 4 6 7 8