pls any one tell me why the loop is not ending??
(program for quick sort)

``````#include<stdio.h>
int partition(int a[],int l,int r);
void quicksort(int a[],int low,int high);
int loc,temp,pivot,a[50],low,high,left,right;
int main()
{
int n,i;
printf("\nEnter the no: of elements : " );
scanf("%d",&n);
printf("\nEnter the numbers  : ");
for(i=0;i<n;i++)
{
printf("   %d ",i);
scanf("%d",&a[i]);
}

//  printf("\n%d %d ok",i,i+900);
low=0;
high=n-1;
quicksort(a,low,high);
for(i=0;i<n;i++)
printf("  %d",a[i]);
return 0;
}

void quicksort(int a[],int low,int high)
{
left=low;
right=high;
while(left<right)
{
loc=partition(a,left,right);
quicksort(a,left,(loc-1));
quicksort(a,(loc+1),right);
}
}

int  partition(int a[50],int l,int r)
{
pivot=a[l];
low=l-1;
high=r+1;
while(low<=high)
{
while(pivot<=a[high]&&low<high)
high=high-1;
while(pivot>=a[low]&&low<high)
low=low+1;
temp=a[high];
a[high]=a[low];
a[low]=temp;
}
loc=low;
temp=a[loc];
a[loc]=a[l];
a[l]=temp;
return loc;
}``````

## All 3 Replies

Please tell me where either left or right are modified in the following loop:

``````while(left<right)
{
loc=partition(a,left,right);
quicksort(a,left,(loc-1));
quicksort(a,(loc+1),right);
}``````

If your answer is "nowhere", then you get a gold star. :) That loop shouldn't be a loop at all, it should be a simple if statement and the recursion handles your "looping".

Also I notice that the loc variable used in while loop in the quick sort is not initialized.

Also I notice that the loc variable used in while loop in the quick sort is not initialized.

It's initialized with the return value of the partition function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.