-1

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);
}
  • 3
    You don't even call quickSort function in your main :) – Karen Melikyan Apr 26 '21 at 12:03
  • 4
    "it's not working" is not a problem description. [Edit] to explain why not, with example input, desired output, and current wrong output. ...or maybe this is just a typo as above. – underscore_d Apr 26 '21 at 12:03
  • 1
    Dikd you read the wikipedia page on [quicksort](https://en.wikipedia.org/wiki/Quicksort) ? Are you allowed to use [`std::sort`](https://en.cppreference.com/w/cpp/algorithm/sort) ? If not, why? Did you read the documentation of your C++ compiler, e.g. [GCC](http://gcc.gnu.org/)? I recommend to compile with `g++ -Wall -Wextra -g` if so allowed. Did you read the documentation of your debugger, e.g. [GDB](https://www.gnu.org/software/gdb/) ? I recommend to read the documentation of your debugger, then to use it – Basile Starynkevitch Apr 26 '21 at 14:14
  • 1
    Does this answer your question? [C++ quick sort algorithm](https://stackoverflow.com/questions/5787964/c-quick-sort-algorithm) –  Apr 26 '21 at 14:20
  • 2
    BTW, except for your `printArray` function, your code smells like C code, not C++ code. Did you read [a good C++ programming book](https://www.stroustrup.com/programming.html)? If not, why? See also [this C++ reference](https://en.cppreference.com/w/cpp) – Basile Starynkevitch Apr 26 '21 at 14:21
  • Please don't suggest me other things I know my code is not perfect I want someone to explain why it's not working. – AnonymousKing Apr 26 '21 at 14:35

1 Answers1

0

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