运行 ❯
获取您
自己的
网站
×
更改方向
更改主题,深色/浅色
前往 Spaces
Python
C
Java
def countingSort(arr): max_val = max(arr) count = [0] * (max_val + 1) while len(arr) > 0: num = arr.pop(0) count[num] += 1 for i in range(len(count)): while count[i] > 0: arr.append(i) count[i] -= 1 return arr unsortedArr = [4, 2, 2, 6, 3, 3, 1, 6, 5, 2, 3] sortedArr = countingSort(unsortedArr) print("Sorted array:", sortedArr) #Python
#include <stdio.h> void countingSort(int arr[], int n) { int max_val = arr[0]; for(int i = 1; i < n; i++) { if(arr[i] > max_val) { max_val = arr[i]; } } int count[max_val + 1]; for(int i = 0; i <= max_val; i++) { count[i] = 0; } for(int i = 0; i < n; i++) { count[arr[i]]++; } int index = 0; for(int i = 0; i <= max_val; i++) { while(count[i] > 0) { arr[index++] = i; count[i]--; } } } int main() { int arr[] = {4, 2, 2, 6, 3, 3, 1, 6, 5, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); countingSort(arr, n); printf("Sorted array: "); for(int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; } //C
public class Main { public static void countingSort(int[] arr) { int max_val = arr[0]; for(int num : arr) { if(num > max_val) { max_val = num; } } int[] count = new int[max_val + 1]; for(int num : arr) { count[num]++; } int index = 0; for(int i = 0; i <= max_val; i++) { while(count[i] > 0) { arr[index++] = i; count[i]--; } } } public static void main(String[] args) { int[] arr = {4, 2, 2, 6, 3, 3, 1, 6, 5, 2, 3}; countingSort(arr); System.out.print("Sorted array: "); for(int num : arr) { System.out.print(num + " "); } System.out.println(); } } //Java
Python 结果
C 结果
Java 结果
排序后的数组:[1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 6]
排序后的数组:1 2 2 2 3 3 3 4 5 6 6
排序后的数组:1 2 2 2 3 3 3 4 5 6 6