Add heap module: array min/max heap with dry runs and bottom-up heapify, PriorityQueue comparators and traps, heap sort, 10 interview problems with brute-force cross-checks (17 tests, 23 transcripts)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4HkWoC7hLzk61vZa8
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
java.util.PriorityQueue in JDK 25.0.5.1+2-LTS (lib/src.zip)
|
||||
===========================================================
|
||||
|
||||
291 private void grow(int minCapacity) {
|
||||
292 int oldCapacity = queue.length;
|
||||
293 // Double size if small; else grow by 50%
|
||||
294 int newCapacity = ArraysSupport.newLength(oldCapacity,
|
||||
295 minCapacity - oldCapacity, /* minimum growth */
|
||||
296 oldCapacity < 64 ? oldCapacity + 2 : oldCapacity >> 1
|
||||
297 /* preferred growth */);
|
||||
298 queue = Arrays.copyOf(queue, newCapacity);
|
||||
299 }
|
||||
|
||||
323 public boolean offer(E e) {
|
||||
324 if (e == null)
|
||||
325 throw new NullPointerException();
|
||||
326 modCount++;
|
||||
327 int i = size;
|
||||
328 if (i >= queue.length)
|
||||
329 grow(i + 1);
|
||||
330 siftUp(i, e);
|
||||
331 size = i + 1;
|
||||
332 return true;
|
||||
333 }
|
||||
|
||||
642 private static <T> void siftUpComparable(int k, T x, Object[] es) {
|
||||
643 Comparable<? super T> key = (Comparable<? super T>) x;
|
||||
644 while (k > 0) {
|
||||
645 int parent = (k - 1) >>> 1;
|
||||
646 Object e = es[parent];
|
||||
647 if (key.compareTo((T) e) >= 0)
|
||||
648 break;
|
||||
649 es[k] = e;
|
||||
650 k = parent;
|
||||
651 }
|
||||
652 es[k] = key;
|
||||
653 }
|
||||
|
||||
725 private void heapify() {
|
||||
726 final Object[] es = queue;
|
||||
727 int n = size, i = (n >>> 1) - 1;
|
||||
728 final Comparator<? super E> cmp;
|
||||
729 if ((cmp = comparator) == null)
|
||||
730 for (; i >= 0; i--)
|
||||
731 siftDownComparable(i, (E) es[i], es, n);
|
||||
732 else
|
||||
733 for (; i >= 0; i--)
|
||||
734 siftDownUsingComparator(i, (E) es[i], es, n, cmp);
|
||||
735 }
|
||||
|
||||
Reference in New Issue
Block a user