Saturday, August 20, 2011

QuickSort using recursion

//QuickSort using recursion
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
main()
{
      int i,*a,n;
      void create(int **a,int n);
      void display(int *a,int n);
      void quicksort(int *a,int lb,int ub);
      extern int quick(int *s,int left,int right);

      a=NULL;
      printf("Enter the number of elements you want in your array : " );
      scanf("%d",&n);
      create(&a,n);
      display(a,n);
      quicksort(a,0,n-1);
      display(a,n);
     getch();
      return 0;
}
void create(int **a,int n)
{
     int i;
     int *s;
     s=(int *)malloc(n*sizeof(int));
     printf("\n Enter the value of array elements " );
     for(i=0;i<n;i++)
     {
                  scanf("%d",&s[i]);
     }
     *a=s;
}
void display(int *a,int n)
{
     int i;
     printf("\n array elements " );
     for(i=0;i<n;i++)
     {
                  printf("%d ",a[i]);
     }
}
void quicksort(int *a,int lb,int ub)
{
     int loc;
     if(lb<ub)
     {
         loc= quick(a,lb,ub);
          quicksort(a,lb,loc-1);
          quicksort(a,loc+1,ub);
     }  
                       
}
int quick(int *s,int left,int right)
{
    int loc,temp;
    loc=left;
    while(1)
    {
            while(s[loc]<=s[right]&&loc!=right)
              {
                  right=right-1;
             
              }
            if(loc==right)
              return loc;
            if(s[loc]>s[right])
            {
               temp=s[loc];
               s[loc]=s[right];
               s[right]=temp;
            }
         
            loc=right;
            while(s[left]<=s[loc]&&loc!=left)
              left=left+1;
            if(loc==left)
              return loc;
            if(s[left]>s[loc])
            {
               temp=s[loc];
               s[loc]=s[left];
               s[left]=temp;
            }
            loc=left;
    }
       
}

Previous Next Home
0 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More