@Override public void sort(@Nonnull T[] a, @Nonnull Comparator<? super T> c) { for (int i = 1; i < a.length; i++) { for (int j = i - 1; j >= 0; j--) { if (c.compare(a[j], a[j + 1]) > 0) { swap(a, j, j + 1); } else { break; } } } } }
public static <T> void heapSort(@Nonnull T[] a, @Nonnull Comparator<? super T> c) { final ArrayBinaryHeap<? super T> heap = heapify(a, c); final int rootIndex = heap.getRootIndex(); for (int i = a.length - 1; i >= 1; i--) { swap(a, i, rootIndex); heap.decreaseSize(); heap.bubbleDown(rootIndex); } } }
swap(numbers, i, j); firstOne = j; allOnes = false;
private void bubbleUp(int currentIndex) { while (true) { final int parentIndex = getParentIndex(currentIndex); if (isValidIndex(parentIndex)) { final T parent = get(parentIndex); final T current = get(currentIndex); if (comparator.compare(parent, current) < 0) { swap(array, parentIndex, currentIndex); currentIndex = parentIndex; } else { // sorted break; } } else { // no parent break; } } }
void bubbleDown(int currentIndex) { final T current = getOrNull(currentIndex); if (current != null) { final int leftIndex = getLeftChildIndex(currentIndex); final T left = getOrNull(leftIndex); final int rightIndex = getRightChildIndex(currentIndex); final T right = getOrNull(rightIndex); int largestIndex = currentIndex; T largest = current; if (left != null && comparator.compare(left, current) > 0) { largestIndex = leftIndex; largest = left; } if (right != null && comparator.compare(right, largest) > 0) { largestIndex = rightIndex; largest = right; } if (largestIndex != currentIndex) { swap(array, largestIndex, currentIndex); bubbleDown(largestIndex); } } }