School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!
 

Code Snippets

  

C Source Code



Sort array using recursion

this code sorts an array using recursion

Submitted By: frog
Actions:
Rating:
Views: 7,828

Language: C

Last Modified: August 11, 2006

Snippet


  1. #include<stdio.h>
  2.  
  3. void quick(int,int);
  4.  
  5. int *array,n,i,c=0;
  6.  
  7. int main()
  8. {
  9.    
  10.    printf(\"Enter number of elements in the array");
  11.    scanf(\"%d\",&n);
  12.    
  13.    array= (int*) calloc(n,sizeof(int));
  14.    
  15.    printf(\"Enter elements \");
  16.      for(int i=1;i<=n;i++)
  17.        scanf(\"%d\",&array[i]);
  18.      
  19.    quick(1,n);
  20.    printf(\"\n\");
  21.    for(i=1;i<=n;i++)
  22.    printf(\"%d \",array[i]);
  23.    printf(\"\n %d\",c);
  24.    
  25.    system("pause");
  26.    return 0;
  27. }
  28. void quick(int x,int y)
  29. {
  30.    int l,k,temp;
  31.    k=x;
  32.    l=y;
  33.    if((y-x)>=1)
  34.      {
  35.        while(l>=x)   
  36.         {
  37.           if(array[k]>array[l]&&k<l)
  38.         {
  39.             c++;
  40.             temp=array[l];
  41.             array[l]=array[k];
  42.             array[k]=temp;
  43.             k=l;
  44.             l--;
  45.         }
  46.           else
  47.             if(array[k]<array[l]&&k>l)
  48.           {
  49.             c++;
  50.             temp=array[l];
  51.             array[l]=array[k];
  52.             array[k]=temp;
  53.             temp=k;
  54.             k=l;
  55.             l=temp;
  56.           }
  57.          else
  58.            l--;
  59.        }
  60.    quick(x,k-1);
  61.    quick(k+1,y);
  62. }
  63. }

Copy & Paste


Comments

There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.