Run ❯
Get your
own
website
×
Change Orientation
Change Theme, Dark/Light
Go to Spaces
Python
C
Java
myArray = [170, 45, 75, 90, 802, 24, 2, 66] print("Original array:", myArray) radixArray = [[], [], [], [], [], [], [], [], [], []] maxVal = max(myArray) exp = 1 while maxVal // exp > 0: while len(myArray) > 0: val = myArray.pop() radixIndex = (val // exp) % 10 radixArray[radixIndex].append(val) for bucket in radixArray: while len(bucket) > 0: val = bucket.pop() myArray.append(val) exp *= 10 print("Sorted array:", myArray) #Python
#include
#include
#define SIZE 8 void radix_sort(int arr[], int size) { int max_val = arr[0]; for(int i = 1; i < size; i++) { if(arr[i] > max_val) { max_val = arr[i]; } } int exp = 1; int *radix_array[10]; for(int i = 0; i < 10; i++) { radix_array[i] = (int *)malloc(sizeof(int) * size); } int counts[10] = {0}; while (max_val / exp > 0) { for(int i = 0; i < size; i++) { int radix_index = (arr[i] / exp) % 10; radix_array[radix_index][counts[radix_index]] = arr[i]; counts[radix_index]++; } int pos = 0; for(int i = 0; i < 10; i++) { for(int j = 0; j < counts[i]; j++) { arr[pos] = radix_array[i][j]; pos++; } counts[i] = 0; } exp *= 10; } for(int i = 0; i < 10; i++) { free(radix_array[i]); } } int main() { int arr[SIZE] = {170, 45, 75, 90, 802, 24, 2, 66}; printf("Original array: "); for(int i = 0; i < SIZE; i++) { printf("%d ", arr[i]); } printf("\n"); radix_sort(arr, SIZE); printf("Sorted array: "); for(int i = 0; i < SIZE; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; } //C
public class Main { public static void main(String[] args) { int[] myArray = {170, 45, 75, 90, 802, 24, 2, 66}; System.out.print("Original array: "); for(int val : myArray) { System.out.print(val + " "); } System.out.println(); int[][] radixArray = new int[10][myArray.length]; int[] counts = new int[10]; int maxVal = findMax(myArray); int exp = 1; while (maxVal / exp > 0) { for(int val : myArray) { int radixIndex = (val / exp) % 10; radixArray[radixIndex][counts[radixIndex]] = val; counts[radixIndex]++; } int pos = 0; for(int i = 0; i < 10; i++) { for(int j = 0; j < counts[i]; j++) { myArray[pos] = radixArray[i][j]; pos++; } counts[i] = 0; } exp *= 10; } System.out.print("Sorted array: "); for(int val : myArray) { System.out.print(val + " "); } System.out.println(); } public static int findMax(int[] arr) { int max = arr[0]; for(int val : arr) { if(val > max) { max = val; } } return max; } } //Java
Python result:
C result:
Java result:
Original array: [170, 45, 75, 90, 802, 24, 2, 66]
Sorted array: [2, 24, 45, 66, 75, 90, 170, 802]
Original array: 170 45 75 90 802 24 2 66
Sorted array: 2 24 45 66 75 90 170 802
Original array: 170 45 75 90 802 24 2 66
Sorted array: 2 24 45 66 75 90 170 802