Skip to content

Instantly share code, notes, and snippets.

@darhonbek
Created October 24, 2017 01:56
Show Gist options
  • Save darhonbek/3fabd9dc0717ee5394baa9e90d8d79f8 to your computer and use it in GitHub Desktop.
Save darhonbek/3fabd9dc0717ee5394baa9e90d8d79f8 to your computer and use it in GitHub Desktop.
Radix Sort
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
void print(int *arr, int n) {
for(register int i=0; i<n; i++) {
cout<<arr[i]<<" ";
}
cout<<"\n";
}
void radixSort(int *arr, int n) {
vector<int> bucks[10];
int max = arr[0];
for(register int i=0; i<n; i++)
if(max < arr[i])
max = arr[i];
register int digit = 0;
register int div = 1;
while(div < max) {
for(register int i=0; i<n; i++) {
digit = (arr[i] / div) % 10;
bucks[digit].push_back(arr[i]);
}
div *= 10;
for(register int i=0, k = 0; i<9, k < n; i++) {
for(register int j=0; j<bucks[i].size(); j++) {
arr[k] = bucks[i].at(j);
k++;
}
bucks[i].clear();
}
print(arr, n);
}
}
int main() {
int arr[] = {5, 6, 0, 13, 3, 2, 8, 7, 4};
int n = 9;
radixSort(arr, n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment