Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

radix sort #5

Merged
merged 1 commit into from
May 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions Java/Algorithm/SortingAlgorithm/radix sort
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;

public class RadixSort {

// Function to find the maximum element in the array
public 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
public static void countSort(int[] arr, int exp) {
int n = arr.length;
int[] output = new int[n]; // output array
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
System.arraycopy(output, 0, arr, 0, n);
}

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

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

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
if (n <= 0) {
throw new IllegalArgumentException("Number of elements must be positive.");
}

int[] arr = new int[n];

System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.println("Original array: " + Arrays.toString(arr));

radixSort(arr);

System.out.println("Sorted array: " + Arrays.toString(arr));
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter integers only.");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
}