Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- using namespace std;
- /**
- * Orders an array of integers with a time complexity of N
- *
- * @author André Souza Abreu
- * @param array An array of integers.
- * @param int The size of the aray.
- * @return void
- */
- void counting_sort(int array[], int array_length) {
- int max_size = -1;
- int min_size = 0;
- for (int i = 0; i < array_length; i++) {
- max_size = max(max_size, array[i] + 1);
- min_size = min(min_size, array[i]);
- }
- int abs_min_size = abs(min_size - 1);
- int blueprintA[max_size], blueprintB[abs_min_size];
- memset(blueprintA, 0, sizeof(blueprintA));
- memset(blueprintB, 0, sizeof(blueprintB));
- for (int i = 0; i < array_length; i++) {
- if (array[i] >= 0) {
- blueprintA[array[i]]++;
- } else {
- blueprintB[-array[i]]++;
- }
- }
- int index = 0;
- // add negative numbers
- for (int i = 0; i < abs_min_size; i++) {
- while (blueprintB[i] != 0) {
- array[index] = -i;
- index++;
- blueprintB[i]--;
- }
- }
- // add positive numbers
- for (int i = 0; i < max_size; i++) {
- while (blueprintA[i] != 0) {
- array[index] = i;
- index++;
- blueprintA[i]--;
- }
- }
- }
- int main () {
- int numbers[10] = {8, 1248, 1248, 532, -412, 67, 3212, 49, 55, 2032};
- counting_sort(numbers, 10);
- for (int i = 0; i < 10; i++) {
- cout << numbers[i] << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement