10000 Arrays, collections and data structures · 2714rohit/Java-Coding-Problems@e4470b6 · GitHub
[go: up one dir, main page]

Skip to content

Commit e4470b6

Browse files
Arrays, collections and data structures
1 parent 05ecffe commit e4470b6

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

Chapter05/P99_SortArray/src/modern/challenge/ArraySorts.java

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,54 @@ void heapify(T[] arr, int n, int i, Comparator<? super T> c) {
437437
}
438438
}
439439

440-
public static void bucketSort(int[] arr) {
440+
/* Bucket sort - Scatter-Sort-Gather approach */
441+
public static void bucketSortSSG(int[] arr) {
442+
443+
if (arr == null) {
444+
throw new IllegalArgumentException("Array cannot be null");
445+
}
446+
447+
int[] hashes = hash(arr);
448+
449+
List<Integer>[] buckets = new List[hashes[1]];
450+
for (int i = 0; i < hashes[1]; i++) {
451+
buckets[i] = new ArrayList();
452+
}
453+
454+
for (int e : arr) {
455+
buckets[hash(e, hashes)].add(e);
456+
}
457+
458+
for (List bucket : buckets) {
459+
Collections.sort(bucket);
460+
}
461+
462+
int p = 0;
463+
for (List<Integer> bucket : buckets) {
464+
for (int j : bucket) {
465+
arr[p++] = j;
466+
}
467+
}
468+
}
469+
470+
private static int[] hash(int[] arr) {
471+
472+
int m = arr[0];
473+
for (int i = 1; i < arr.length; i++) {
474+
if (m < arr[i]) {
475+
m = arr[i];
476+
}
477+
}
478+
479+
return new int[]{m, (int) Math.sqrt(arr.length)};
480+
}
481+
482+
private static int hash(int num, int[] hashes) {
483+
return (int) ((double) num / hashes[0] * (hashes[1] - 1));
484+
}
485+
486+
/* Bucket sort - Scatter-Gather approach */
487+
public static void bucketSortSG(int[] arr) {
441488

442489
if (arr == null) {
443490
throw new IllegalArgumentException("Array cannot be null");

0 commit comments

Comments
 (0)
0