Skip to content

Commit 2935775

Browse files
authored
Add files via upload
1 parent ce3f2cc commit 2935775

File tree

2 files changed

+123
-0
lines changed

2 files changed

+123
-0
lines changed

Sorting Technique/13 Countsort.c

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include <stdio.h>
2+
#include<stdlib.h>
3+
int findMax(int A[], int n) // fxn for finding max from array A // so that we can create a count array of max size
4+
{
5+
int max = -2147483647;
6+
int i;
7+
for (i = 0; i < n; i++)
8+
{
9+
if (A[i] > max)
10+
max = A[i];
11+
}
12+
return max;
13+
}
14+
void CountSort(int A[], int n)
15+
{
16+
int i, j, max, * C;
17+
18+
max = findMax(A, n); // find max element from array
19+
C = (int*)malloc(sizeof(int) * (max + 1)); // creatring count array of max size
20+
21+
for (i = 0; i < max + 1; i++) // intialise all count array with zero
22+
{
23+
C[i] = 0;
24+
}
25+
for (i = 0; i < n; i++) // count the no of elements present and increment the count array index
26+
{
27+
C[A[i]]++;
28+
}
29+
30+
i = 0; j = 0;
31+
while (j < max + 1) // copy all the elements back to A
32+
{
33+
if (C[j] > 0)
34+
{
35+
A[i++] = j;
36+
C[j]--;
37+
}
38+
else
39+
j++;
40+
}
41+
}
42+
int main()
43+
{
44+
int A[] = { 11,13,7,12,16,9,24,5,10,3 }, n = 10, i;
45+
46+
CountSort(A, n);
47+
48+
for (i = 0; i < 10; i++)
49+
printf("%d ", A[i]);
50+
printf("\n");
51+
52+
return 0;
53+
}
54+
// time comlexity O (n ) // less time taken // but it is space counsuming algorithm // when the value of elements will be less we will opt this algo
+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include <iostream>
2+
3+
using namespace std;
4+
5+
template <class T>
6+
void Print(T& vec, int n, string s){
7+
cout << s << ": [" << flush;
8+
for (int i=0; i<n; i++){
9+
cout << vec[i] << flush;
10+
if (i < n-1){
11+
cout << ", " << flush;
12+
}
13+
}
14+
cout << "]" << endl;
15+
}
16+
17+
int Max(int A[], int n){
18+
int max = -32768;
19+
for (int i=0; i<n; i++){
20+
if (A[i] > max){
21+
max = A[i];
22+
}
23+
}
24+
return max;
25+
}
26+
27+
void CountSort(int A[], int n){
28+
int max = Max(A, n);
29+
30+
// Create count array
31+
int* count = new int [max + 1];
32+
33+
// Initialize count array with 0
34+
for (int i=0; i<max+1; i++){
35+
count[i] = 0;
36+
}
37+
38+
// Update count array values based on A values
39+
for (int i=0; i<n; i++){
40+
count[A[i]]++;
41+
}
42+
43+
// Update A with sorted elements
44+
int i = 0;
45+
int j = 0;
46+
while (j < max+1){
47+
if (count[j] > 0){
48+
A[i++] = j;
49+
count[j]--;
50+
} else {
51+
j++;
52+
}
53+
}
54+
55+
// Delete heap memory
56+
delete [] count;
57+
}
58+
59+
int main() {
60+
61+
int A[] = {2, 5, 8, 12, 3, 6, 7, 10};
62+
int n = sizeof(A)/sizeof(A[0]);
63+
64+
Print(A, n, "\t\tA");
65+
CountSort(A, n);
66+
Print(A, n, " Sorted A");
67+
68+
return 0;
69+
}

0 commit comments

Comments
 (0)