|
| 1 | +package com.thealgorithms.sorts; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * Implementation of Block Sort algorithm that implements the SortAlgorithm interface. |
| 7 | + * |
| 8 | + * Block Sort is a distribution sorting algorithm that divides the array into blocks, |
| 9 | + * sorts each block, and merges the blocks to produce a sorted array. |
| 10 | + * |
| 11 | + * The method works as follows: |
| 12 | + * <ol> |
| 13 | + * <li>Divide the input array into blocks.</li> |
| 14 | + * <li>Sort each block individually.</li> |
| 15 | + * <li>Merge the sorted blocks to produce a fully sorted array.</li> |
| 16 | + * </ol> |
| 17 | + */ |
| 18 | +public class BlockSort implements SortAlgorithm { |
| 19 | + |
| 20 | + @Override |
| 21 | + public <T extends Comparable<T>> T[] sort(T[] array) { |
| 22 | + return blockSort(array); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * Sorts an array using the Block Sort algorithm. |
| 27 | + * |
| 28 | + * @param arr the array to be sorted. |
| 29 | + * @param <T> the type of elements to be sorted, must be comparable. |
| 30 | + * @return the sorted array. |
| 31 | + */ |
| 32 | + private <T extends Comparable<? super T>> T[] blockSort(T[] arr) { |
| 33 | + if (arr.length <= 1) { |
| 34 | + return arr; // Already sorted |
| 35 | + } |
| 36 | + |
| 37 | + int blockSize = (int) Math.sqrt(arr.length); // Block size is the square root of the array size |
| 38 | + int numBlocks = (arr.length + blockSize - 1) / blockSize; // Calculate number of blocks |
| 39 | + |
| 40 | + // Create an array of blocks |
| 41 | + T[][] blocks = (T[][]) new Comparable[numBlocks][]; |
| 42 | + |
| 43 | + // Populate the blocks |
| 44 | + for (int i = 0; i < numBlocks; i++) { |
| 45 | + int start = i * blockSize; |
| 46 | + int end = Math.min(start + blockSize, arr.length); |
| 47 | + blocks[i] = Arrays.copyOfRange(arr, start, end); |
| 48 | + Arrays.sort(blocks[i]); // Sort each block |
| 49 | + } |
| 50 | + |
| 51 | + // Merge the sorted blocks |
| 52 | + return mergeBlocks(blocks); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Merges sorted blocks into a single sorted array. |
| 57 | + * |
| 58 | + * @param blocks the array of sorted blocks. |
| 59 | + * @param <T> the type of elements in the blocks, must be comparable. |
| 60 | + * @return the merged sorted array. |
| 61 | + */ |
| 62 | + private <T extends Comparable<? super T>> T[] mergeBlocks(T[][] blocks) { |
| 63 | + int totalLength = Arrays.stream(blocks).mapToInt(b -> b.length).sum(); |
| 64 | + T[] result = (T[]) new Comparable[totalLength]; |
| 65 | + int index = 0; |
| 66 | + |
| 67 | + for (T[] block : blocks) { |
| 68 | + for (T element : block) { |
| 69 | + result[index++] = element; // Add each element from the block to the result array |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return result; |
| 74 | + } |
| 75 | +} |
0 commit comments