Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions Sorting Algorithms/counting-sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// C++ Program for counting sort
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
#define RANGE 255
void countSort(char arr[]){
char output[strlen(arr)];

int count[RANGE + 1], i;
memset(count, 0, sizeof(count));

for(i = 0; arr[i]; ++i)
++count[arr[i]];
for (i = 1; i <= RANGE; ++i)
count[i] += count[i-1];

for (i = 0; arr[i]; ++i){
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}

for (i = 0; arr[i]; ++i)
arr[i] = output[i];
}
int main(){
char arr[] = "helloworld";
countSort(arr);
cout<< "Sorted character array is " << arr;
return 0;
}
43 changes: 43 additions & 0 deletions Sorting Algorithms/radix.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// C++ implementation of Radix Sort
#include<iostream>
using namespace std;
int getMax(int arr[], int n){
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
void countSort(int arr[], int n, int exp){
int output[n]; // output array
int i, count[10] = {0};
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--){
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
void radixsort(int arr[], int n){
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
void print(int arr[], int n){
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];
radixsort(arr, n);
print(arr, n);
return 0;
}