Advertisement
mehedi1

Bucket sort.cpp

Jul 14th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void bucketSort(double A[], int n) {
  5.     vector<double> bucket[n];
  6.     for(int i=0;i<n;++i) {
  7.         bucket[int(n*A[i])].push_back(A[i]);
  8.     }
  9.     for(int i=0;i<n;++i) {
  10.         sort(bucket[i].begin(), bucket[i].end());
  11.     }
  12.     int k=0;
  13.     for(int i=0;i<n;++i) {
  14.         for(int j=0;j<bucket[i].size();++j) {
  15.             A[k++] = bucket[i][j];
  16.         }
  17.     }
  18. }
  19. int main() {
  20.     int n;
  21.     cin>>n;
  22.     double A[n];
  23.     for(int i=0;i<n;++i) cin>>A[i];
  24.     bucketSort(A, n);
  25.     for(int i=0;i<n;++i) cout<<A[i]<<" ";
  26.     return 0;
  27. }
  28.  
  29. /*
  30. 10
  31. 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
  32. */
  33.  
  34. /*
  35. BUCKET_SORT(A)
  36.     let B[0..n-1] be a new array
  37.     n = A.length
  38.     for I = 0 to n-1
  39.         make B[i] an empty list
  40.     for i=1 to n
  41.         insert a[i] into b[floor(n*a[i])]
  42.     for I = 0 to n-1
  43.         sort b[i] using insertion sort
  44.     concatenate list b[0],b[1]…b[n-1] together in order
  45.  
  46. // Algorithm source from Introduction to Algorithms by CLRC
  47. */
  48.  
  49. /*
  50. T(n) = [time to insert n elements in array A] + [time to go through auxiliary array B[0 . . n-1] * (Sort by INSERTION_SORT)
  51.        = O(n) + (n-1)  (n)
  52.        = O(n)
  53. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement