Program work 13. Heap Sort in Java

本文详细介绍了堆排序的基本概念,包括最大堆的建立与重构方法,并提供了完整的Java实现代码。通过对堆排序算法的深入解析,帮助读者理解其运行机制及时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关键在于最大堆的建立和重构 (其实两个过程是一样的)

因为堆是平衡二叉树, 所以数组可以直接用下标表示父子的节点关系, 数组要从下标1开始.

将最大值移到数组只需要O(n)

重构堆需要O(lgn)

所以upper bound is O(n*logn)

事实上, lower bound is  Ω(n*logn) 

最好最坏最差都是O(n*logn)


Pseudocode

heapSort (arr, len)
{
    buildMaxHeap()
    for () {
        remove the root element(the max) to the end of array
        reconstructHeap();
    }
}

reconsturctHeap(arr, len)
{
    tmp = arr[root]
    get the children of root
    while () {
        get the bigger child between left and right child
        if the element of that child is larger than root
            replace its parent element with is
        move to next children
    }
    place the tmp to the apporpriate pos
}

Java

package ncku.cdc.sorting;

import java.util.Random;

public class HeapSort {
  private int[] sequence;

  public HeapSort(int size, int range) {
    sequence = new int[size + 1];
    Random rand = new Random();
    for (int i = 1; i <= size; i++) {
      sequence[i] = rand.nextInt(range);
    }
  }

  public static void main(String[] args) {
    int size = Integer.valueOf(args[0]);
    int range = Integer.valueOf(args[1]);
    HeapSort heap = new HeapSort(size, range);

    System.out.println("before heapSort:");
    SortingTools.validation(heap.getSequence(), 1);
    
    heap.heapSort(heap.getSequence(), size);

    System.out.println("after heapSort:");
    SortingTools.validation(heap.getSequence(), 1);
  }
  
  public void heapSort(int[] arr, int len) {
    for (int i = len / 2; i > 0; i--) {
      retifyHeap(arr, i, len);
    }
    for (int j = len - 1; j > 0; j--) {
      swap(arr, 1, j + 1);
      retifyHeap(arr, 1, j);
    }
  }

  private void retifyHeap(int[] arr, int root, int len) {
    int tmp = arr[root];
    int child = root * 2;
    while (child <= len) {
      if ((child < len) && (arr[child] < arr[child + 1])) { child++; }
      if (tmp > arr[child]) { break; } 
      else {
        arr[child / 2] = arr[child];
        child *= 2;
      }
    }
    arr[child / 2] = tmp;
  }
  
  private void swap(int[] arr, int i, int j) {
    int t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
  }

  public int[] getSequence() {
    return sequence;
  }
}


程序输入: 35 200. 表示随机生成一个长度为35, 数字范围在[0, 200)的数组

程序输出:

before heapSort:
67 18 192 142 136 30 144 6 158 11 123 34 36 155 97 12 7 159 81 135 160 102 48 42 0 155 77 114 139 146 186 32 42 144 100 
after heapSort:
0 6 7 11 12 18 30 32 34 36 42 42 48 67 77 81 97 100 102 114 123 135 136 139 142 144 144 146 155 155 158 159 160 186 192

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值