-
Notifications
You must be signed in to change notification settings - Fork 256
/
Copy path13 Count Sort.cpp
74 lines (69 loc) · 1.55 KB
/
13 Count Sort.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
68
69
70
71
72
73
74
#include<iostream>
using namespace std;
struct Array
{
int* A;
int size;
int length;
};
void Display(struct Array* arr)
{
int i;
cout << "The elements of the array is " << endl;
for (i = 0; i < arr->length; i++)
cout << arr->A[i] << " ";
}
int Findmax(struct Array* arr) // findinf the max of the array
{
int a = INT_MIN;
int i;
for (i = 0; i < arr->length; i++)
{
if (arr->A[i] > a)
a = arr->A[i];
}
return a;
}
void Countsort(struct Array* arr)
{
int max, i;
int* C;
max = Findmax(arr); // finding the max element of the array
C = new int[max + 1]; // create an array of max size element in the array
for (i = 0; i < max + 1; i++)
C[i] = 0; // initialize all the count array with zero
for (i = 0; i < arr->length; i++)
{
C[arr->A[i]]++; // count the number of element present in the array and increament count
}
int j;
i = 0, j = 0;
while (i < max + 1)// with this loop depending on the count of the elements will be filled in the array in sorted manner
{
if (C[i] > 0) {
arr->A[j++] = i;
C[i]--;
}
else
i++;
}
}
int main()
{
struct Array arr;
cout << "Enter the size of the Array" << endl;
cin >> arr.size;
arr.A = new int[arr.size];
int no, i;
cout << "Enter the length of the Array " << endl;
cin >> no;
arr.length = 0;
cout << "Enter the elements of the Array" << endl;
for (i = 0; i < no; i++)
cin >> arr.A[i];
arr.length = no;
Countsort(&arr);
//cout<<"The max of the array is -> "<<Findmax(&arr);
Display(&arr);
return 0;
}