-
Notifications
You must be signed in to change notification settings - Fork 344
/
Copy pathcountingsort_negative.cpp
67 lines (53 loc) · 1.29 KB
/
countingsort_negative.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// counting sort implementation
#include <iostream>
#include <algorithm>
using namespace std;
void counting_sort(int arr[], int size)
{
int max = *max_element(arr, arr + size);
int min = *min_element(arr, arr + size);
int range = max - min + 1;
int count[range] = {0};
// counting frequency of numbers in array
for (int i = 0; i < size; i++)
{
count[arr[i] - min]++;
}
// calculating cumulative sum
for (int i = 1; i < range; i++)
{
count[i] += count[i - 1];
}
int output[size];
// making the new sorted array
for (int i = size - 1; i >= 0; i--) // traversing from backward for stability
{
output[count[arr[i]-min] - 1] = arr[i];
count[arr[i]-min]--;
}
// copying the sorted array in original array
for (int i = 0; i < size; i++)
{
arr[i] = output[i];
}
}
int main()
{
int size;
cout << "\nenter size of the array : ";
cin >> size;
int arr[size];
cout << "Start entering values in array (numeric type) : ";
for (int i = 0; i < size; i++)
{
cout << i + 1 << ") ";
cin >> arr[i];
}
counting_sort(arr, size);
cout << "After sorting : ";
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
return 0;
}