Skip to content

Instantly share code, notes, and snippets.

@Magnus167
Created July 14, 2023 21:42
Show Gist options
  • Save Magnus167/1fe0fd2ce107c15f8f5a3a759e7be448 to your computer and use it in GitHub Desktop.
Save Magnus167/1fe0fd2ce107c15f8f5a3a759e7be448 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#define MAX 256
#define INT_BITS 32
void countingSort(int arr[], int n, int exp) {
int output[n]; // output array
int i, count[MAX] = {0};
for (i = 0; i < n; i++)
count[(arr[i] >> exp) & (MAX - 1)]++;
for (i = 1; i < MAX; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--) {
output[count[(arr[i] >> exp) & (MAX - 1)] - 1] = arr[i];
count[(arr[i] >> exp) & (MAX - 1)]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
void radixsort(int arr[], int n) {
for (int exp = 0; exp < INT_BITS; exp += 8)
countingSort(arr, n, exp);
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n);
printArray(arr, n);
return 0;
}
# https://chat.openai.com/share/06e83721-73ed-4174-a0fb-c385ff7396d0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment