0

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;
}

Edited by WaltP: Added CODE Tags -- please use them.

3
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by Narue
0

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".

Edited by Narue: n/a

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.