# quick sort implementation causing mysterious error

Discussion in 'C' started by k0der, Jun 9, 2009.

1. ### k0derNew Member

Joined:
Apr 14, 2009
Messages:
19
0
Trophy Points:
0
the code for the quicksort that i implemented is as below :
Code:
```
//******************** this routine implements quick sort taking first element as the pivot *******************

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

main()
{
int elements[]={24,5,50,10,1,55,95,80},j;
void quick(int *array,int left,int right);
int left,right,pivot;
left=0;
right=7;

for(j=left;j<=right;j++)         //print the array befor sorting:W

printf("%d\t",elements[j]);

quick(elements,left,right);
printf("\nthe sorted array is :\n");
for(left=0;left<=right;left++)
printf("%d\t",elements[left]);
printf("\n");

}
void quick(int el[],int left,int right)
{
int pivot=0,tmp,i=left-1,j=right;  // j increased and i dec for looping convenience
int num=right-left+1;             //num of elements

// swapping the last element and pivot ;is first element
tmp=el[pivot];
el[pivot]=el[right];
el[right]=tmp;

//now comparing the elements from the pivot
pivot=right;                        //pivot has become the index for the rightmost element
printf("\n pivot : %d\n",el[pivot]);

for( ; ; )
{
while(el[++i] > el[pivot])
{
printf("\n el[i]=%d \n",el[i]);
break;
}

while(el[--j] < el[pivot])
{
printf("\n el[j]=%d \n",el[j]);
break;
}

if(fflush(NULL) != 0  )
printf("\n %s \n",strerror(errno));
if(i>j)
break;
else
{
tmp=el[i];
el[i]=el[j];
el[j]=tmp;

printf("\n----after swap-----\n");      // looking at list here for debugging purpose

for(tmp=left;tmp<=right;tmp++)
printf("%d\t",el[tmp]);
}
}

tmp=el[pivot];        //for i>j case
el[pivot]=el[i];
el[i]=tmp;

printf("\n ---Aafter sStep-----\n");
for(j=left;j<=right;j++)
printf("%d\t",el[j]);

sleep(5);     // for debugging purpose

if(left<i)
quick(el,left,i-1);

if(right>i)
quick(el,i+1,right);
}
```

the output is not sorted.and error is still there but where i am not able to find.
thanks for help.

Last edited by a moderator: Jun 9, 2009
2. ### SaswatPadhi~ Б0ЯИ Τ0 С0δЭ ~

Joined:
May 5, 2009
Messages:
1,343
55
Trophy Points:
0
Occupation:
STUDENT !
Location:
Orissa, INDIA
Please edit your post and post the code inside code-blocks. (so as to preserve the indentation).

3. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,012
203
Trophy Points:
63
Occupation:
Senior Support Engineer
Location:
England

Joined:
Apr 14, 2009
Messages:
19