Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdlib.h>
- #include<conio.h>
- #include<stdio.h>
- void swap(int *p,int *q)
- {
- int temp=*p;
- *p=*q;
- *q=temp;
- }
- void printarray(int a[],int n)
- {
- int i;
- for (i=0;i<n;i++)
- printf("%d, ",a[i]);
- }
- int partition(int a[],int l,int h,char ch)
- {
- int pivot,i,j;
- pivot=a[l];
- i=l;j=h;
- while(i<j)
- {
- if(ch=='2'){
- do
- {
- i++;
- }while(a[i]>=pivot);
- do
- {
- j--;
- }while(a[j]<pivot);
- if(i<j)
- swap(&a[i],&a[j]);
- }
- else if(ch=='1')
- {
- do
- {
- i++;
- }while(a[i]<=pivot);
- do
- {
- j--;
- }while(a[j]>pivot);
- if(i<j)
- swap(&a[i],&a[j]);
- }
- }
- swap(&a[l],&a[j]);
- return j;
- }
- void quick_sort(int a[],int i,int j,int ch)
- {
- int loc;
- if(i<j)
- {
- loc=partition(a,i,j,ch);
- quick_sort(a,i,loc,ch);
- quick_sort(a,loc+1,j,ch);
- }
- }
- main()
- {
- int a[20],n,i;
- char ch;
- printf("enter the size of array : ");
- scanf("%d",&n);
- for(i=0;i<n;i++)
- {
- printf("enter the data : ");
- scanf("%d",&a[i]);
- }
- while(1)
- {
- printf("\n1>sort ascending\n2> sort descending\n3> exit\nenter your choice : ");
- fflush(stdin);
- ch=getche();
- if(ch=='1')
- printf("the array sorted in ascending order is : ");
- else if(ch=='2')
- printf("the array sorted in descending order is : ");
- else{exit(0);}
- quick_sort(a,0,n,ch);
- printarray(a,n);
- }
- }
Add Comment
Please, Sign In to add comment