Created
June 17, 2018 11:42
-
-
Save hanshsieh/a4ba935be17b9bba6a4094f26f970f39 to your computer and use it in GitHub Desktop.
Example code for heapify an array of integers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Random; | |
class Heapifier { | |
private int[] nums; | |
/** | |
* Rearrange the elements in the given array so that it satisfy min heap property. | |
* Time comlexity: O(N) | |
*/ | |
public void minHeapify(int[] nums) { | |
this.nums = nums; | |
int nowIdx = getParentOf(nums.length - 1); | |
while (nowIdx >= 0) { | |
siftDown(nowIdx); | |
nowIdx--; | |
} | |
} | |
private void siftDown(int nowIdx) { | |
while (true) { | |
int swapIdx = nowIdx; | |
int leftChildIdx = getLeftChildOf(nowIdx); | |
if (leftChildIdx >= nums.length) { | |
break; | |
} | |
if (nums[swapIdx] > nums[leftChildIdx]) { | |
swapIdx = leftChildIdx; | |
} | |
int rightChildIdx = getRightChildOf(nowIdx); | |
if (rightChildIdx < nums.length && nums[swapIdx] > nums[rightChildIdx]) { | |
swapIdx = rightChildIdx; | |
} | |
if (swapIdx == nowIdx) { | |
break; | |
} | |
swap(swapIdx, nowIdx); | |
nowIdx = swapIdx; | |
} | |
} | |
private void swap(int idx1, int idx2) { | |
int tmp = nums[idx1]; | |
nums[idx1] = nums[idx2]; | |
nums[idx2] = tmp; | |
} | |
private static int getLeftChildOf(int idx) { | |
return idx * 2 + 1; | |
} | |
private static int getRightChildOf(int idx) { | |
return idx * 2 + 2; | |
} | |
private static int getParentOf(int idx) { | |
return (idx - 1) / 2; | |
} | |
public static void main(String[] args) { | |
Heapifier heapifier = new Heapifier(); | |
Random random = new Random(); | |
for (int i = 0; i < 100000; ++i) { | |
int size = random.nextInt(100); | |
int[] nums = new int[size]; | |
Arrays.parallelSetAll(nums, (idx) -> random.nextInt(size)); | |
heapifier.minHeapify(nums); | |
verifyHeap(nums); | |
} | |
} | |
private static void verifyHeap(int[] nums) { | |
for (int i = 0; i < nums.length; ++i) { | |
int leftChildIdx = getLeftChildOf(i); | |
int rightChildIdx = getRightChildOf(i); | |
if (leftChildIdx < nums.length && nums[leftChildIdx] < nums[i]) { | |
throw new AssertionError("Element at index " + i + " is larger than index " + leftChildIdx); | |
} | |
if (rightChildIdx < nums.length && nums[rightChildIdx] < nums[i]) { | |
throw new AssertionError("Element at index " + i + " is larger than index " + leftChildIdx); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment