Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1118 from Kuljeet-123/counting
Counting Sort
- Loading branch information
Showing
2 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
Data Structure/Array Or Vector/Counting Sort/SolutionByKuljeet.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
#include <iostream> | ||
#include <algorithm> | ||
using namespace std; | ||
|
||
void countSort(int arr[], int n, int k) | ||
{ | ||
int count[n]; | ||
for(int i = 0;i < k;i++) | ||
count[i] = 0; | ||
|
||
for(int i = 0;i < n;i++) | ||
count[arr[i]]++; | ||
|
||
for(int i = 1;i < k;i++) | ||
count[i] = count[i-1] + count[i]; | ||
|
||
int output[n]; | ||
for(int i = n-1;i >= 0;i--) | ||
{ | ||
output[count[arr[i]]-1] = arr[i]; | ||
count[arr[i]]--; | ||
} | ||
|
||
for(int i = 0;i < n;i++) | ||
arr[i] = output[i]; | ||
|
||
for(int i = 0;i < n;i++) | ||
cout << arr[i] << " "; | ||
|
||
} | ||
|
||
int main() | ||
{ | ||
int n; | ||
cin >> n; | ||
int arr[n]; | ||
for(int i = 0;i < n;i++) | ||
cin >> arr[i]; | ||
|
||
int k; | ||
cin >> k; | ||
countSort(arr,n,k); | ||
return 0; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
# An unsorted array is given sort the array using counting sort. | ||
|
||
# Constraints | ||
- 1 < size Of Array <= 10^6 | ||
- 0 < Array Elements <= 10^9 | ||
|
||
# Input | ||
- Array | ||
- Its Size | ||
|
||
# Output | ||
- Print the sorted array. | ||
|
||
``` | ||
Input : {12, 11, 13, 5, 6, 7} | ||
Output : { 5, 6, 7, 11, 12, 13, } | ||
``` | ||
|