|
| 1 | +package com.thealgorithms.sorts; |
| 2 | + |
| 3 | +/** |
| 4 | + * Library Sort (also known as Gapped Insertion Sort) is traditionally implemented |
| 5 | + * using periodic gaps between elements for faster insertion. This implementation |
| 6 | + * uses binary search to find the insertion position combined with array shifting, |
| 7 | + * which is a simplified variant without gap-based optimization. |
| 8 | + * Time Complexity: O(n^2) worst case due to element shifting |
| 9 | + * Space Complexity: O(n) |
| 10 | + * |
| 11 | + * @see <a href="https://en.wikipedia.org/wiki/Library_sort"> |
| 12 | + * Wikipedia: Library Sort</a> |
| 13 | + * @author Vraj Prajapati (@Rosander0) |
| 14 | + */ |
| 15 | +public final class LibrarySort { |
| 16 | + |
| 17 | + private LibrarySort() { |
| 18 | + // Utility class |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Sorts an array using the Library Sort algorithm. |
| 23 | + * |
| 24 | + * @param array the array to sort (must not be null) |
| 25 | + * @return the sorted array |
| 26 | + * @throws IllegalArgumentException if {@code array} is {@code null} |
| 27 | + */ |
| 28 | + public static int[] sort(final int[] array) { |
| 29 | + if (array == null) { |
| 30 | + throw new IllegalArgumentException("Input array must not be null."); |
| 31 | + } |
| 32 | + if (array.length <= 1) { |
| 33 | + return array; |
| 34 | + } |
| 35 | + |
| 36 | + int n = array.length; |
| 37 | + Integer[] spaced = new Integer[2 * n]; |
| 38 | + |
| 39 | + spaced[0] = array[0]; |
| 40 | + int inserted = 1; |
| 41 | + |
| 42 | + for (int i = 1; i < n; i++) { |
| 43 | + int pos = binarySearch(spaced, inserted, array[i]); |
| 44 | + for (int j = inserted; j > pos; j--) { |
| 45 | + spaced[j] = spaced[j - 1]; |
| 46 | + } |
| 47 | + spaced[pos] = array[i]; |
| 48 | + inserted++; |
| 49 | + } |
| 50 | + |
| 51 | + int idx = 0; |
| 52 | + for (int i = 0; i < 2 * n; i++) { |
| 53 | + if (spaced[i] != null) { |
| 54 | + array[idx++] = spaced[i]; |
| 55 | + } |
| 56 | + } |
| 57 | + return array; |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Binary search to find insertion position among inserted elements. |
| 62 | + * |
| 63 | + * @param spaced the spaced array |
| 64 | + * @param inserted number of elements inserted so far |
| 65 | + * @param target the value to find position for |
| 66 | + * @return the correct insertion index |
| 67 | + */ |
| 68 | + private static int binarySearch(final Integer[] spaced, |
| 69 | + final int inserted, final int target) { |
| 70 | + int lo = 0; |
| 71 | + int hi = inserted; |
| 72 | + while (lo < hi) { |
| 73 | + int mid = lo + (hi - lo) / 2; |
| 74 | + if (spaced[mid] <= target) { |
| 75 | + lo = mid + 1; |
| 76 | + } else { |
| 77 | + hi = mid; |
| 78 | + } |
| 79 | + } |
| 80 | + return lo; |
| 81 | + } |
| 82 | +} |
0 commit comments