1、优先队列的实现

  1. package priority_queue;
  2. /**
  3. * @author zwlstart
  4. * @create 2020-12-25 10:41
  5. */
  6. import java.util.Objects;
  7. /**
  8. * 基于堆这个结构,实现优先队列·
  9. */
  10. public class MaxPQ{
  11. //表示优先队列的大小
  12. int n;
  13. //用数组表示完全二叉树,表示一个堆,从1下标开始表示
  14. int[] pq;
  15. public MaxPQ(int max){
  16. pq = new int[max + 1];
  17. n = max;
  18. }
  19. public MaxPQ(int[] array){
  20. pq = new int[array.length + 1];
  21. n = 0;
  22. for (int i = 0; i < array.length; i++) {
  23. insert(array[i]);
  24. }
  25. }
  26. /**
  27. * 向优先队列中插入一个元素,插入之后也需满足堆的性质,即父节点大于等于子节点
  28. * @param e
  29. */
  30. public void insert(int e){
  31. pq[++n] = e;
  32. int k = n;
  33. while (k > 1 && pq[k] > pq[k / 2]){
  34. int temp = pq[k];
  35. pq[k] = pq[k /2];
  36. pq[k / 2] = temp;
  37. k /= 2;
  38. }
  39. }
  40. public int getMax(){
  41. return pq[1];
  42. }
  43. //删除一个元素,删除之后也需满足堆的性质
  44. public int delMax(){
  45. int e = pq[1];
  46. pq[1] = pq[n--];
  47. int k = 1;
  48. while (2 * k <= n){
  49. int j = 2 * k;
  50. if (j < n && pq[j]< pq[j + 1]){
  51. j++;
  52. }
  53. if (pq[k] > pq[j]){
  54. break;
  55. }
  56. int temp = pq[j];
  57. pq[j] = pq[k];
  58. pq[k] = temp;
  59. k = j;
  60. }
  61. return e;
  62. }
  63. public boolean isEmpty(){
  64. return n == 0;
  65. }
  66. public int size(){
  67. return n;
  68. }
  69. }

2、运用优先队列得到堆排序

  1. package priority_queue;
  2. /**
  3. * @author zwlstart
  4. * @create 2020-12-25 11:26
  5. */
  6. public class HeapSort {
  7. /**
  8. * 堆排序,利用优先队列进行实现
  9. * @param array
  10. */
  11. public static void sort(int[] array){
  12. MaxPQ maxPQ = new MaxPQ(array);
  13. int n = array.length;
  14. while (!maxPQ.isEmpty()){
  15. int i = maxPQ.delMax();
  16. array[--n] = i;
  17. }
  18. }
  19. }