I have made quick sort for the first time without seeing any code just by seeing the animation, but the solution is not what I am expecting. can any one tell me what I am doing wrong in this code? because as per me the algorithm should work, but it's not working. please point out my mistake. if you can it would be very helpful.
my code
#include<iostream>
using namespace std;
void printArray(int arr[]){
for(int i = 0 ;i<8;i++){
cout<<arr[i]<<endl;
}
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
int partioner(int array[],int low, int high){
int k = low;
int piv =array[0];
int i =low+1;
int j =high;
while(j>i){
while(piv<array[j]){
j--;}
while(piv>array[i]){
i++;}
if(i<j){
swap(&array[i],&array[j]);}}
swap(&array[low],&array[j]);
return j;
}
void quickSort(int array[],int low,int high)
{
if(low<high){
int loc=partioner(array,low,high);
quickSort(array,low,loc-1);
quickSort(array,loc+1,high);
}
}
int main(){
int array[] = {8,7,6,5,4,3,2,1};
quickSort(array,0,7);
printArray(array);
}
In your partioner()
function, it should have been:
int piv = array[low];
Instead of :
int piv = array[0];
Further reading : Quick sort - Geeksforgeeks
Side note : If you're using C++, maybe take a look at sort()
: sort() - cplusplus.com