MCPcopy Create free account
hub / github.com/Manvityagi/PW-Skills-Java-Course-Codes / Main

Class Main

Lecture 43 Non-Comparison Sorting/src/Main.java:3–117  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import java.util.*;
2
3public class Main {
4 public static void bbucketSort(float[] arr) {
5 //Let's create 10 buckets
6 ArrayList<ArrayList<Float>> buckets = new ArrayList<>();
7 // Initialize each bucket
8 for (int i = 0; i < 10; i++) {
9 buckets.add(new ArrayList<>());
10 }
11 // Dividing arr into buckets
12 for (int i = 0; i < arr.length; i++) {
13 int index;
14 if (arr[i] >= 1) {
15 index = ((int) arr[i]) % 10;
16 } else {
17 index = (int) (arr[i] * 10);
18 }
19 buckets.get(index).add(arr[i]);
20 }
21 // Sorting each bucket
22 for (int i = 0; i < 10; i++) {
23 Collections.sort(buckets.get(i));
24 }
25 // Merging buckets together
26 int index = 0;
27 for (int bucket = 0; bucket < 10; bucket++) {
28 ArrayList<Float> currBucket = buckets.get(bucket);
29 for (int i = 0; i < currBucket.size(); i++) {
30 arr[index++] = currBucket.get(i);
31 }
32 }
33 }
34 static int findMax(int[] arr) {
35 int max = arr[0];
36 for (int i = 1; i < arr.length; i++) {
37 if (arr[i] > max) max = arr[i];
38 }
39 return max;
40 }
41 static void countSort(int[] arr, int place) {
42 int n = arr.length;
43 int[] output = new int[n];
44 int[] count = new int[10];
45 for (int i = 0; i < n; i++) { // Store the count of each element
46 count[(arr[i] / place) % 10]++;
47 }
48 for (int i = 1; i < count.length; i++) { // prefix sum
49 count[i] += count[i - 1];
50 }
51 // Find the index of each element of the original arr in count arr, and place the elements in output arr
52 for (int i = n - 1; i >= 0; i--) {
53 int idx = count[(arr[i] / place) % 10] - 1;
54 output[idx] = arr[i];
55 count[(arr[i] / place) % 10]--;
56 }
57 for (int i = 0; i < n; i++) {
58 arr[i] = output[i];
59 }
60 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected