# QUICKSORT not working as required.

#include<stdio.h>
#include<stdlib.h>

``````int partition(int *a,int p, int q)
{
int key=a[q],t,i,j=q-1;
i=p;
while(i<j){

while(a[i]<key&&i<q)
i++;
while(a[j]>key&&j>=p)
j--;

if(i<j){
t=a[i];
a[i]=a[j];
a[j]=t;
}

}
if(i>j&&j>=p){
t=a[j];
a[j]=a[q];
a[q]=t;
}

return j;
}

void quicksort(int *a,int ll, int ul){
int pos;
if(ll<ul){
pos=partition(a,ll,ul);
quicksort(a,ll,pos-1);
quicksort(a,pos+1,ul);
}
}

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

quicksort(a,0,n-1);
for(i=0;i<n;i++)
printf("%d  ",a[i]);

return 0;
}``````

Simple example: [45, 23]
You have only two numbers in here. So, in the very first call to partition, `p=0` and `q=1`
Now, `key=a[q](=23), i=p(=0), j=q-1(=0)`

Now, `while (i<j)` and `if (i > j && ...)` are both false. So, it will return `j(=0)`, and the partition is done (according to this implementation). But, the element at a[j] is 45, and there are still elements to tis right (23) which are smaller than this pivot element. So, the partitioning is wrong.

You might want to recheck the algorithm, whether you have mistyped some variable somewhere or not.

PS: if there is a repeat until construct in algorithm, like

``````repeat
X
until C
``````

then, it is translated into C code as

``````do {
X
} while (!C);
``````

Note that,

1. it is `do...while` in action and not `while`
2. the condition C is negated in the `do...while`