Skip to content

Commit a1460b4

Browse files
added counting sort
1 parent fc4c69d commit a1460b4

File tree

2 files changed

+51
-7
lines changed

2 files changed

+51
-7
lines changed

Sorting Algorithms/CountingSort.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
void CountingSort(int arr[], int n)
5+
{
6+
7+
auto it = max_element(arr, arr + n); // Finding Max Element O(n) time
8+
int max = *it;
9+
cout << max << endl;
10+
int count[max + 1] = {0};
11+
12+
for (int i = 0; i < n; i++)
13+
{
14+
count[arr[i]]++;
15+
}
16+
17+
int i = 0, k = 0;
18+
while (i <= max)
19+
{
20+
if (count[i] >= 1)
21+
{
22+
arr[k] = i;
23+
k++;
24+
count[i]--;
25+
}
26+
else
27+
{
28+
i++;
29+
}
30+
}
31+
}
32+
33+
int main()
34+
{
35+
36+
int arr[] = {4, 5, 3, 8, 34, 9, 34, 267, 54, 4};
37+
int n = 10;
38+
39+
for (auto x : arr)
40+
cout << x << " ";
41+
cout << endl;
42+
CountingSort(arr, n);
43+
for (auto x : arr)
44+
cout << x << " ";
45+
cout << endl;
46+
47+
return 0;
48+
}

Sorting Algorithms/MergeSort.cpp

+3-7
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ void Merge(int arr[], int l, int mid, int h)
1515
L[i] = arr[l + i];
1616
for (j = 0; j < n2; j++)
1717
R[j] = arr[mid + 1 + j];
18-
i = 0; // Initial index of first subarray
19-
j = 0; // Initial index of second subarray
20-
k = l; // Initial index of merged subarray
18+
i = 0;
19+
j = 0;
20+
k = l;
2121
while (i < n1 && j < n2)
2222
{
2323
if (L[i] <= R[j])
@@ -33,17 +33,13 @@ void Merge(int arr[], int l, int mid, int h)
3333
k++;
3434
}
3535

36-
/* Copy the remaining elements of L[], if there
37-
are any */
3836
while (i < n1)
3937
{
4038
arr[k] = L[i];
4139
i++;
4240
k++;
4341
}
4442

45-
/* Copy the remaining elements of R[], if there
46-
are any */
4743
while (j < n2)
4844
{
4945
arr[k] = R[j];

0 commit comments

Comments
 (0)