Run ❯
Get your
own
website
×
Change Orientation
Change Theme, Dark/Light
Go to 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
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 result:
C result:
Java result:
Sorted array: [1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 6]
Sorted array: 1 2 2 2 3 3 3 4 5 6 6
Sorted array: 1 2 2 2 3 3 3 4 5 6 6