Gilgamesh858

CountingSort.cpp

Feb 9th, 2016
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4.  
  5. using namespace std;
  6.  
  7. void countingSort(int *A, int n)
  8. {
  9.     int min = A[0];
  10.     int max = A[0];
  11.     for(int i=1; i < n; i++)
  12.     {
  13.         if( A[i] > max ) max = A[i];
  14.         if( A[i] < min ) min = A[i];
  15.     }
  16.    
  17.     int range = max-min+1;
  18.     int *C = new int[range];
  19.     for( int i = 0; i < range; i++ ) C[i] = 0;
  20.     for( int i = 0; i < n; i++) C[A[i]-min]++;
  21.    
  22.     int j = 0;
  23.     for(int k = 0; k < range; k++)
  24.         while(C[k] > 0)
  25.         {
  26.             A[j++] = k+min;
  27.             C[k]--;
  28.         }
  29. }
  30.  
  31. void print(int *A, int n)
  32. {
  33.     cout << "A: ";
  34.     for(int i = 0; i < n; i++)
  35.         cout << A[i] << " ";
  36.        
  37.     cout << endl << endl;
  38. }
  39.  
  40. int main()
  41. {
  42.     int n = rand()%2000+1;
  43.     //int A[] = {5, 7, 12, 45, 21, 2, 3, 20, 18, 13};
  44.     int A[n];
  45.     srand(time(NULL));
  46.     for(int i = 0; i < n; i++)
  47.         A[i] = rand()%10000+1;
  48.     print(A, n);
  49.     countingSort(A, n);
  50.     print(A,n);
  51.    
  52.     return 0;
  53. }
Add Comment
Please, Sign In to add comment