@@ -17,8 +17,6 @@ private LibrarySort() {
1717 // Utility class
1818 }
1919
20- private static final int GAP = 1 ;
21-
2220 /**
2321 * Sorts an array using the Library Sort algorithm.
2422 *
@@ -34,30 +32,22 @@ public static int[] sort(final int[] array) {
3432 }
3533
3634 int n = array .length ;
37- // Allocate spaced array with gaps between each element
38- int spacedSize = n * (GAP + 1 );
39- Integer [] spaced = new Integer [spacedSize ];
35+ Integer [] spaced = new Integer [2 * n ];
4036
41- // Insert first element
4237 spaced [0 ] = array [0 ];
43-
4438 int inserted = 1 ;
4539
4640 for (int i = 1 ; i < n ; i ++) {
47- // Binary search for correct position among inserted elements
4841 int pos = binarySearch (spaced , inserted , array [i ]);
49-
50- // Shift elements right by GAP+1 to make room
5142 for (int j = inserted ; j > pos ; j --) {
5243 spaced [j ] = spaced [j - 1 ];
5344 }
5445 spaced [pos ] = array [i ];
5546 inserted ++;
5647 }
5748
58- // Collect sorted elements back
5949 int idx = 0 ;
60- for (int i = 0 ; i < spacedSize ; i ++) {
50+ for (int i = 0 ; i < 2 * n ; i ++) {
6151 if (spaced [i ] != null ) {
6252 array [idx ++] = spaced [i ];
6353 }
@@ -78,7 +68,7 @@ private static int binarySearch(final Integer[] spaced, final int inserted, fina
7868 int hi = inserted ;
7969 while (lo < hi ) {
8070 int mid = lo + (hi - lo ) / 2 ;
81- if (spaced [mid ] != null && spaced [ mid ] <= target ) {
71+ if (spaced [mid ] <= target ) {
8272 lo = mid + 1 ;
8373 } else {
8474 hi = mid ;
0 commit comments