标签:
最近复习数据结构,又回去再看塞神的课件,看到PriorityQueue的实现。自己也根据塞神的代码写一写。
下面使用Binary Heap实现了一个简单的 Max-oriented PriorityQueue。
public class MaxPQ { public Integer[] elements; public int N; public MaxPQ(int size) { elements = new Integer[size + 1]; N = 0; // index starts with 1 } public void insert(Integer x) { elements[++N] = x; swim(N); } private void swim(int k) { while (k > 1 && elements[k] > elements[k / 2]) { swap(k, k / 2); k /= 2; } } public Integer delMax() { Integer max = elements[1]; swap(1, N--); elements[N + 1] = null; sink(1); return max; } private void sink(int k) { while (2 * k <= N) { int j = 2 * k; if (j < N && elements[j] < elements[j + 1]) { j++; } if (elements[j] < elements[k]) { break; } swap(k, j); k = j; } } public Integer peek() { return elements[1]; } public boolean isEmpty() { return N == 0; } private void swap(int i, int j) { Integer tmp = elements[i]; elements[i] = elements[j]; elements[j] = tmp; } public void shuffle() { // for testing java.util.Random rand = new java.util.Random(System.currentTimeMillis()); for (int i = 1; i <= N; i++) { int r = 1 + rand.nextInt(i); swap(i, r); } } public void heapify() { // for testing for (int k = N / 2; k >= 1; k--) { sink(k); } } public void heapSort() { heapify(); int n = N; while (n > 1) { swap(1, n--); sink(1); } } }
上面是用Binary heap设计一个 Max-oriented Priority Queue, 数组是1-based。 假如遇到面试官问怎么heapify怎么办? 下面我们就对上面代码进行少许改动,变为0-based,可以直接对数组进行max - heapify。
public static void heapify(int[] nums) { if (nums == null) { return; } for (int k = nums.length / 2; k >= 1; k--) { sink(nums, k); } } private static void sink(int[] nums, int k) { int len = nums.length; while (2 * k <= len) { int j = 2 * k; if (j < len && nums[j - 1] < nums[j]) { j++; } if (nums[k - 1] > nums[j - 1]) { break; } swap(nums, k - 1, j - 1); k = j; } } private static void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; }
Test Client:
public static void main(String[] args) { int len = 10; int[] nums = new int[len]; for (int i = 0; i < len; i++) { nums[i] = i + 1; } shuffle(nums); for (int i : nums) { System.out.print(i + " "); } heapify(nums); System.out.println(); for (int i : nums) { System.out.print(i + " "); } }
Reference:
http://algs4.cs.princeton.edu/24pq/
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/5290262.html