From b343e121902cc097703589e555ad3c8726763498 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=89=B4=E5=AE=A2?= Date: Mon, 18 May 2020 17:14:12 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9F=BA=E6=95=B0=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/RadixSort.java | 52 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/RadixSort.java diff --git a/src/RadixSort.java b/src/RadixSort.java new file mode 100644 index 0000000..215965c --- /dev/null +++ b/src/RadixSort.java @@ -0,0 +1,52 @@ +/** + * 基数排序 + */ +public class RadixSort { + private static int getMax(int[] a ){ + int max = a[0]; + for (int i : a){ + if (i > max){ + max = i; + } + } + return max; + } + private static void countSort(int[] a, int exp){ + int[] output = new int[a.length]; + int[] buckets = new int[10]; + for (int anA : a) { + buckets[(anA / exp) % 10]++; + } + for (int i : buckets) + System.out.print(i + " "); + System.out.println(); + for (int i = 1; i < 10; i++){ + buckets[i] += buckets[i - 1]; + } + for (int i : buckets) + System.out.print(i + " "); + System.out.println(); + for (int i = a.length - 1; i >= 0; i--){ + output[buckets[(a[i] / exp) % 10] - 1] = a[i]; + buckets[(a[i] / exp) % 10]--; + } + for (int i = 0; i < a.length; i++){ + a[i] = output[i]; + } + output = null; + buckets = null; + } + private static void radixSort(int[] a){ + int max = getMax(a); + for (int exp = 1; max / exp > 0; exp *= 10){ + countSort(a, exp); + } + } + public static void main(String[] args){ + int[] a = {53, 3, 542, 748, 14, 214, 154, 63, 616}; + radixSort(a); + for (int i : a){ + System.out.print(i + " "); + } + } +} \ No newline at end of file