Arnab_Manna

quick sort mine optimised

Jun 22nd, 2020
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. #include<stdlib.h>
  2. #include<conio.h>
  3. #include<stdio.h>
  4.  
  5. void swap(int *p,int *q)
  6. {
  7.     int temp=*p;
  8.     *p=*q;
  9.     *q=temp;
  10. }
  11.  
  12. void printarray(int a[],int n)
  13.  {
  14.     int i;
  15.     for (i=0;i<n;i++)
  16.          printf("%d, ",a[i]);
  17.  }
  18.  
  19. int partition(int a[],int l,int h,char ch)
  20. {
  21.     int pivot,i,j;
  22.     pivot=a[l];
  23.     i=l;j=h;
  24.     while(i<j)
  25.     {
  26.         if(ch=='2'){
  27.         do
  28.         {
  29.             i++;
  30.         }while(a[i]>=pivot);
  31.    
  32.         do
  33.         {
  34.             j--;
  35.         }while(a[j]<pivot);
  36.         if(i<j)
  37.         swap(&a[i],&a[j]);
  38.         }
  39.         else if(ch=='1')
  40.         {
  41.             do
  42.         {
  43.             i++;
  44.         }while(a[i]<=pivot);
  45.    
  46.         do
  47.         {
  48.             j--;
  49.         }while(a[j]>pivot);
  50.         if(i<j)
  51.         swap(&a[i],&a[j]); 
  52.         }
  53.        
  54.         }
  55.         swap(&a[l],&a[j]);
  56.         return j;
  57.    
  58.    
  59. }
  60.    
  61. void quick_sort(int a[],int i,int j,int ch)
  62. {
  63.     int loc;
  64.     if(i<j)
  65.     {
  66.         loc=partition(a,i,j,ch);
  67.         quick_sort(a,i,loc,ch);
  68.         quick_sort(a,loc+1,j,ch);
  69.     }
  70. }
  71.  
  72. main()
  73. {
  74.     int a[20],n,i;
  75.     char ch;
  76.     printf("enter the size of array : ");
  77.     scanf("%d",&n);
  78.     for(i=0;i<n;i++)
  79.     {
  80.         printf("enter the data : ");
  81.         scanf("%d",&a[i]);
  82.     }
  83.     while(1)
  84.     {
  85.     printf("\n1>sort ascending\n2> sort descending\n3> exit\nenter your choice : ");
  86.     fflush(stdin);
  87.     ch=getche();
  88.     if(ch=='1')
  89.     printf("the array sorted in ascending order is : ");
  90.     else if(ch=='2')
  91.     printf("the array sorted in descending order is : ");
  92.     else{exit(0);}
  93.     quick_sort(a,0,n,ch);
  94.     printarray(a,n);
  95.     }
  96. }
Add Comment
Please, Sign In to add comment