import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr = {5, 3, 8, 1, 2}; Arrays.sort(arr); for (int num : arr) { System.out.print(num + " "); } } }
The Arrays.sort method in Java uses a comparison based sorting algorithm (Dual-Pivot Quicksort for primitives) which sorts the array in ascending order.
import java.util.Arrays; public class Main { public static void countingSort(int[] arr) { int max = Arrays.stream(arr).max().getAsInt(); int[] count = new int[max + 1]; for (int num : arr) { count[num]++; } int index = 0; for (int i = 0; i < count.length; i++) { while (count[i] > 0) { arr[index++] = i; count[i]--; } } } public static void main(String[] args) { int[] arr = {4, 2, 2, 8, 3, 3, 1}; countingSort(arr); for (int num : arr) { System.out.print(num + " "); } } }
Counting sort is a non comparison based sorting algorithm that counts the frequency of each element and reconstructs the sorted array.
Comparison based sorting algorithms have a theoretical lower bound of O(n log n) for worst case. Non comparison based algorithms like Counting Sort or Radix Sort can achieve O(n) when input constraints allow.
import java.util.*; public class Main { public static void radixSort(int[] arr) { int max = Arrays.stream(arr).max().getAsInt(); for (int exp = 1; max / exp > 0; exp *= 10) { countingSortByDigit(arr, exp); } } private static void countingSortByDigit(int[] arr, int exp) { int n = arr.length; int[] output = new int[n]; int[] count = new int[10]; for (int i = 0; i < n; i++) { count[(arr[i] / exp) % 10]++; } for (int i = 1; i < 10; i++) { count[i] += count[i - 1]; } for (int i = n - 1; i >= 0; i--) { int digit = (arr[i] / exp) % 10; output[count[digit] - 1] = arr[i]; count[digit]--; } System.arraycopy(output, 0, arr, 0, n); } public static void main(String[] args) { int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; radixSort(arr); for (int num : arr) { System.out.print(num + " "); } } }
Radix sort is a non comparison based sorting algorithm that sorts numbers by processing individual digits using counting sort as a subroutine.
Counting Sort is efficient when the range of input values (k) is small compared to the number of elements (n), achieving O(n + k) time, which can be faster than comparison based sorts.
