堆排序算法

排序(Heap Sort)是另外一个比较快的排序算法,时间复杂度和快速排序算法属于同一级别,只不过系数要大些。

在我的机器上用堆排序100万个随机整数花费3.3秒,而快速排序(QuickSort)需要1.6秒。

package cn.tenyears.demo;

/**
 * implements the heap sort
 
 @author taolue
 
 */
public class Heap {

  private Comparable[] arrList;

  private int maxSize = 0;

  private int heapSize = 0;

  // sort the array
  public static void heapSort(Comparable[] arr) {
    Heap heap = new Heap(arr);
    Comparable com;
    int size = arr.length;
    for (int i = size - 1; i >= 1; i--) {
      com = heap.delete();
      arr[i= com;
    }
  }

  public Heap(int max) {
    arrList = new Comparable[max];
    maxSize = max;
    heapSize = 0;
  }

  public Heap(Comparable[] arr) {
    maxSize = arr.length;
    heapSize = maxSize;
    arrList = arr;
    int curPos = (heapSize - 22;
    while (curPos >= 0) {
      goDown(curPos);
      curPos--;
    }
  }

  public void insert(Comparable com) {
    if (heapSize == maxSize)
      return;
    arrList[heapSize= com;
    goUp(heapSize);
    heapSize++;
  }

  public Comparable delete() {
    Comparable com;
    if (heapSize == 0)
      return null;
    com = arrList[0];
    arrList[0= arrList[heapSize - 1];
    heapSize--;
    goDown(0);
    return com;
  }

  public boolean isFull() {
    return this.maxSize == this.heapSize;
  }

  public boolean isEmpty() {
    return this.heapSize == 0;
  }

  @SuppressWarnings("unchecked")
  private void goUp(int i) {
    int curPos = i;
    int parentPos = (curPos - 12;
    Comparable com = arrList[curPos];
    while (curPos != 0) {
      if (arrList[parentPos].compareTo(com0)
        break;
      else {
        arrList[curPos= arrList[parentPos];
        curPos = parentPos;
        parentPos = (curPos - 12;
      }
    }
  }

  @SuppressWarnings("unchecked")
  private void goDown(int i) {
    int curPos = i;
    int childPos = * curPos + 1;
    Comparable com = arrList[curPos];
    while (childPos < heapSize) {
      if ((childPos + < heapSize)
          && arrList[childPos + 1].compareTo(arrList[childPos]) 0)
        childPos = childPos + 1;
      if (com.compareTo(arrList[childPos]) 0)
        break;
      else {
        arrList[curPos= arrList[childPos];
        curPos = childPos;
        childPos = * curPos + 1;
      }
    }
    arrList[curPos= com;
  }

  public static void main(String[] args) {
    int size = 1000000;
    Integer[] a = new Integer[size];
    for (int i = 0; i < size; i++)
      a[i= Integer.valueOf((intMath.round(Math.random() * size));
    long start = System.currentTimeMillis();
    heapSort(a);
    /*
    Heap heap = new Heap(a);
    while(!heap.isEmpty()) {
      System.out.println(heap.delete());
    }
    */
    long end = System.currentTimeMillis();
    System.out.println("Last: " (end - start" ms");
  }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值