运行 ❯
获取您
自己
的网站
×
更改方向
更改主题,深色/浅色
前往 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 <stdio.h> #include <stdlib.h> #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 结果
C 结果
Java 结果
原始数组: [170, 45, 75, 90, 802, 24, 2, 66]
排序后的数组: [2, 24, 45, 66, 75, 90, 170, 802]
原始数组: 170 45 75 90 802 24 2 66
排序后的数组: 2 24 45 66 75 90 170 802
原始数组: 170 45 75 90 802 24 2 66
排序后的数组: 2 24 45 66 75 90 170 802