BEGINNER, HELP MY QUICKSORT PLEASE :|

Guys, I need Help for my Quicksort.
Whenever I run it in CodeBlocks, It reaches to a stage where the whole thing just stops working.

I’m a beginner so don’t judge :smiley:

#include <iostream>
#include<stdlib.h>
#include<cstdio>
#include<conio.h>
using namespace std;


int* qsort(int a[30],int l,int r)
   { int y,g,p,x,z;
       if(l!=r){
                        //l is left limit  r is right limit
     p=l;               // p is pivot
     y=l+1;
     g=y;               // y  is a start of lower than pivot  
                         // g is upper part of pivot
     z=g;                // z is a counter
     while(z!=r)
     {
         if(a[z]<=a[p])
         {   x=a[y];
             a[y]=a[z];     //swapping
             a[z]=x;

             z++;y++;g++;
         }
         else if(a[z]>a[p])
         {
             g++;z++;
         }
         else
            ;
     }
     x=a[p];
     a[p]=a[y-1];  // swapping pivot
     a[y-1]=a[p];

   }
   qsort(a,p,y-1); // recursive calls
   qsort(a,y,g);

   return a;   // returning array. I'm not sure about this :(

   }





int main()
{
    int n;
    scanf("%d",&n);

    int a[30];

    for(int i=0;i<n;i++)
     scanf("%d",&a[i]);

     system("cls");

    for(int i=0;i<n;i++)  //  printing the array just to see if it works.
     printf("%d\n",a[i]);


     qsort(a,0,n-1);


     for(int i=0;i<n;i++)
     printf("%d\n",a[i]);
    return 0;
}

Its hard to debug your code. The code is very shabbily written. I would recommend the following link for a nice and neat implementation of qsort. https://www.hackerearth.com/practice/notes/sorting-code-monk/

1 Like

sorry i did’nt read your full code so i can’t tell u the exact error but on a quick look it seems like it is because you are declaring only a single method for partition as well as quicksort i recommend using a seprate method for recursive calls also check whether p<y-1 and y<g before calling qsort recursively

1 Like