From 5b20e75e1e85c43f071d71144e25a276b3681bbc Mon Sep 17 00:00:00 2001 From: Nupur1306 <146502280+Nupur1306@users.noreply.github.com> Date: Mon, 16 Oct 2023 21:39:02 +0530 Subject: [PATCH] Create Radix Sort Using Java It's a code to sort an array or linked list by using radix sort. --- Radix Sort Using Java | 56 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Radix Sort Using Java diff --git a/Radix Sort Using Java b/Radix Sort Using Java new file mode 100644 index 0000000..148d3f1 --- /dev/null +++ b/Radix Sort Using Java @@ -0,0 +1,56 @@ +import java.util.Arrays; + +class RadixSort +{ +void countingSort(int array[], int size, int place) + { + int[] output = new int[size + 1]; + int max = array[0]; + for (int i = 1; i < size; i++) { + if (array[i] > max) + max = array[i]; + } + int[] count = new int[max + 1]; + + for (int i = 0; i < max; ++i) + count[i] = 0; + for (int i = 0; i < size; i++) + count[(array[i] / place) % 10]++; + for (int i = 1; i < 10; i++) + count[i] += count[i - 1]; + for (int i = size - 1; i >= 0; i--) + { + output[count[(array[i] / place) % 10] - 1] = array[i]; + count[(array[i] / place) % 10]--; + } + + for (int i = 0; i < size; i++) + array[i] = output[i]; +} + +int getMax(int array[], int n) +{ + int max = array[0]; + for (int i = 1; i < n; i++) + if (array[i] > max) + max = array[i]; + return max; +} + +void radixSort(int array[], int size) +{ + int max = getMax(array, size); + for (int place = 1; max / place > 0; place *= 10) + countingSort(array, size, place); +} + +public static void main(String args[]) +{ + int[] data = { 121, 432, 564, 23, 1, 45, 788 }; + int size = data.length; + RadixSort rs = new RadixSort(); + rs.radixSort(data, size); + System.out.println("Sorted Array in Ascending Order: "); + System.out.println(Arrays.toString(data)); +} +}