diff --git a/Sorting Algorithms/counting-sort.cpp b/Sorting Algorithms/counting-sort.cpp new file mode 100644 index 0000000..c290601 --- /dev/null +++ b/Sorting Algorithms/counting-sort.cpp @@ -0,0 +1,30 @@ +// C++ Program for counting sort +#include +#include +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; +} \ No newline at end of file diff --git a/Sorting Algorithms/radix.cpp b/Sorting Algorithms/radix.cpp new file mode 100644 index 0000000..6b983d9 --- /dev/null +++ b/Sorting Algorithms/radix.cpp @@ -0,0 +1,43 @@ +// C++ implementation of Radix Sort +#include +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<>n; + int arr[n]; + for(int i=0;i>arr[i]; + radixsort(arr, n); + print(arr, n); + return 0; +} \ No newline at end of file