From 68da5c2297d113bd32d337dcbc129a014b980267 Mon Sep 17 00:00:00 2001 From: Chetan Verma <82757233+chetannverma@users.noreply.github.com> Date: Sat, 1 Oct 2022 17:36:23 +0530 Subject: [PATCH] bucket-sorting in java --- Java/bucket_sort. java | 53 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Java/bucket_sort. java diff --git a/Java/bucket_sort. java b/Java/bucket_sort. java new file mode 100644 index 0000000..79969ed --- /dev/null +++ b/Java/bucket_sort. java @@ -0,0 +1,53 @@ +// Java program to sort an array +// using bucket sort +import java.util.*; +import java.util.Collections; + +class abc { + static void bucketSort(float arr[], int n) + { + if (n <= 0) + return; + + + @SuppressWarnings("unchecked") + Vector[] buckets = new Vector[n]; + + for (int i = 0; i < n; i++) { + buckets[i] = new Vector(); + } + + + for (int i = 0; i < n; i++) { + float idx = arr[i] * n; + buckets[(int)idx].add(arr[i]); + } + + + for (int i = 0; i < n; i++) { + Collections.sort(buckets[i]); + } + + int index = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < buckets[i].size(); j++) { + arr[index++] = buckets[i].get(j); + } + } + } + + public static void main(String args[]) + { + float arr[] = { (float)0.897, (float)0.565, + (float)0.656, (float)0.1234, + (float)0.665, (float)0.3434 }; + + int n = arr.length; + bucketSort(arr, n); + + System.out.println("Sorted array is "); + for (float el : arr) { + System.out.print(el + " "); + } + } +}