Advertisement
gitman3

p4b | quick_sort

Mar 12th, 2023
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. void swap(int *a,int *b){
  5. int t=*a;
  6. *a=*b;
  7. *b=t;
  8. }
  9.  
  10. int partition(int A[],int l,int h){
  11. int i=l-1,j=h+1,pi=rand()%(h-l+1)+l;
  12. while(1){
  13. while(i<h && A[++i]<A[pi]);
  14. while(j>l && A[--j]>A[pi]);
  15. if(i>=j) return j;
  16. swap(&A[i],&A[j]);
  17. }
  18. }
  19.  
  20. void quick_sort(int A[],int l,int h){
  21. if(l<h){
  22. int p=partition(A,l,h);
  23. quick_sort(A,l,p);
  24. quick_sort(A,p+1,h);
  25. }
  26. }
  27.  
  28. int main(){
  29. int n;
  30. printf("Enter number of elements: ");
  31. scanf("%d",&n);
  32. int A[n];
  33. printf("Enter the elements: ");
  34. for(int i=0;i<n;i++) scanf("%d",&A[i]);
  35. quick_sort(A,0,n-1);
  36. for(int i=0;i<n;i++) printf("%d ",A[i]);
  37. printf("\n");
  38. return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement