Advertisement
Tariqul_Islam

Quick sort

Jul 30th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int partition(int a[],int left,int right)
  6.  
  7. {
  8.  
  9. int x=a[right];
  10.  
  11. int i=left-1;
  12.  
  13. for(int j=left; j<right; j++)
  14.  
  15. {
  16.  
  17. if(a[j]<=x)
  18.  
  19. {
  20.  
  21. i++;
  22.  
  23. swap(a[i],a[j]);
  24.  
  25. }
  26.  
  27. }
  28.  
  29. swap(a[right],a[i+1]);
  30.  
  31. return i+1;
  32.  
  33. }
  34.  
  35. void quicksort(int a[],int left,int right)
  36.  
  37. {
  38.  
  39. if(left<right)
  40.  
  41. {
  42.  
  43. int q=partition(a,left,right);
  44.  
  45. quicksort(a,left,q-1);
  46.  
  47. quicksort(a,q+1,right);
  48.  
  49. }
  50.  
  51. }
  52.  
  53. int main()
  54.  
  55. {
  56.  
  57. int n;
  58.  
  59. cin>>n;
  60.  
  61. int a[n];
  62.  
  63. for(int i=0; i<n; i++)
  64.  
  65. {
  66.  
  67. cin>>a[i];
  68.  
  69. }
  70.  
  71. quicksort(a,0,n-1);
  72.  
  73. for(int i=0; i<n; i++)
  74.  
  75. {
  76.  
  77. cout<<a[i]<<" ";
  78.  
  79. }
  80.  
  81. return 0;
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement