siddeshshewde / Algorithms

Help beginners learn the Git workflow and start contributing to Open Source!
6 stars 19 forks source link

Radix Sort #55

Open git-sumana opened 9 months ago

git-sumana commented 9 months ago

import java.util.Arrays;

public class RadixSort {

// A utility function to get the maximum value in arr[]
static int getMax(int arr[]) {
    int max = arr[0];
    for (int i = 1; i < arr.length; i++)
        if (arr[i] > max)
            max = arr[i];
    return max;
}

// A function to do counting sort of arr[] according to
// the digit represented by exp.
static void countSort(int arr[], int exp) {
    int n = arr.length;
    int output[] = new int[n];
    int count[] = new int[10];
    Arrays.fill(count, 0);

    // Store count of occurrences in count[]
    for (int i = 0; i < n; i++)
        count[(arr[i] / exp) % 10]++;

    // Change count[i] so that count[i] now contains
    // actual position of this digit in output[]
    for (int i = 1; i < 10; i++)
        count[i] += count[i - 1];

    // Build the output array
    for (int i = n - 1; i >= 0; i--) {
        output[count[(arr[i] / exp) % 10] - 1] = arr[i];
        count[(arr[i] / exp) % 10]--;
    }

    // Copy the output array to arr[], so that arr[] now
    // contains sorted numbers according to the current digit
    for (int i = 0; i < n; i++)
        arr[i] = output[i];
}

// The main function to that sorts arr[] using Radix Sort
static void radixSort(int arr[]) {
    int max = getMax(arr);

    // Do counting sort for every digit. Note that instead
    // of passing digit number, exp is passed. exp is 10^i
    // where i is current digit number
    for (int exp = 1; max / exp > 0; exp *= 10)
        countSort(arr, exp);
}

// A utility function to print an array
static void printArray(int arr[]) {
    for (int i : arr) System.out.print(i + " ");
    System.out.println();
}

// Driver code
public static void main(String[] args) {
    int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
    System.out.println("Original array:");
    printArray(arr);

    radixSort(arr);

    System.out.println("\nSorted array:");
    printArray(arr);
}

}

// Original array: 170 45 75 90 802 24 2 66 // Sorted array: 2 24 45 66 75 90 170 802