MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / sort

Method sort

src/main/java/com/thealgorithms/sorts/SmoothSort.java:40–107  ·  view source on GitHub ↗

Sorts the given array in ascending order using Smooth Sort. @param array the array to sort @param the element type @return the sorted array

(final T[] array)

Source from the content-addressed store, hash-verified

38 * @return the sorted array
39 */
40 @Override
41 public <T extends Comparable<T>> T[] sort(final T[] array) {
42 if (array.length < 2) {
43 return array;
44 }
45
46 final int last = array.length - 1;
47
48 // The forest shape is encoded as (p, pshift): p is a bit-vector of present tree orders,
49 // shifted right by pshift. pshift is the order of the rightmost (current) Leonardo tree.
50 long p = 1L;
51 int pshift = 1;
52
53 int head = 0;
54 while (head < last) {
55 if ((p & 3L) == 3L) {
56 sift(array, pshift, head);
57 p >>>= 2;
58 pshift += 2;
59 } else {
60 // Add a new singleton tree; if it will not be merged anymore, we must fully trinkle.
61 if (LEONARDO[pshift - 1] >= last - head) {
62 trinkle(array, p, pshift, head, false);
63 } else {
64 // This tree will be merged later, so it is enough to restore its internal heap property.
65 sift(array, pshift, head);
66 }
67
68 if (pshift == 1) {
69 // If L(1) is used, the new singleton is L(0).
70 p <<= 1;
71 pshift = 0;
72 } else {
73 // Otherwise, shift to order 1 and append a singleton of order 1.
74 p <<= (pshift - 1);
75 pshift = 1;
76 }
77 }
78
79 p |= 1L;
80 head++;
81 }
82
83 trinkle(array, p, pshift, head, false);
84
85 // Repeatedly remove the maximum (always at head) by shrinking the heap region.
86 while (pshift != 1 || p != 1L) {
87 if (pshift <= 1) {
88 // Rightmost tree is a singleton (order 0 or 1). Move to the previous tree root.
89 final long mask = p & ~1L;
90 final int shift = Long.numberOfTrailingZeros(mask);
91 p >>>= shift;
92 pshift += shift;
93 } else {
94 // Split a tree of order (pshift) into two children trees of orders (pshift-1) and (pshift-2).
95 p <<= 2;
96 p ^= 7L;
97 pshift -= 2;

Callers

nothing calls this directly

Calls 2

siftMethod · 0.95
trinkleMethod · 0.95

Tested by

no test coverage detected