Advertisement
andresouzaabreu

counting sort

Apr 4th, 2020
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. using namespace std;
  5.  
  6. /**
  7.  * Orders an array of integers with a time complexity of N
  8.  *
  9.  * @author André Souza Abreu
  10.  * @param array An array of integers.
  11.  * @param int The size of the aray.
  12.  * @return void
  13. */
  14. void counting_sort(int array[], int array_length) {
  15.     int max_size = -1;
  16.     int min_size = 0;
  17.     for (int i = 0; i < array_length; i++) {
  18.         max_size = max(max_size, array[i] + 1);
  19.         min_size = min(min_size, array[i]);
  20.     }
  21.     int abs_min_size = abs(min_size - 1);
  22.  
  23.     int blueprintA[max_size], blueprintB[abs_min_size];
  24.     memset(blueprintA, 0, sizeof(blueprintA));
  25.     memset(blueprintB, 0, sizeof(blueprintB));
  26.  
  27.     for (int i = 0; i < array_length; i++) {
  28.         if (array[i] >= 0) {
  29.             blueprintA[array[i]]++;
  30.         } else {
  31.             blueprintB[-array[i]]++;
  32.         }
  33.     }
  34.  
  35.     int index = 0;
  36.  
  37.     // add negative numbers
  38.     for (int i = 0; i < abs_min_size; i++) {
  39.         while (blueprintB[i] != 0) {
  40.             array[index] = -i;
  41.             index++;
  42.             blueprintB[i]--;
  43.         }
  44.     }
  45.  
  46.     // add positive numbers
  47.     for (int i = 0; i < max_size; i++) {
  48.         while (blueprintA[i] != 0) {
  49.             array[index] = i;
  50.             index++;
  51.             blueprintA[i]--;
  52.         }
  53.     }
  54. }
  55.  
  56. int main () {
  57.     int numbers[10] = {8, 1248, 1248, 532, -412, 67, 3212, 49, 55, 2032};
  58.  
  59.     counting_sort(numbers, 10);
  60.  
  61.     for (int i = 0; i < 10; i++) {
  62.         cout << numbers[i] << endl;
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement