堆排序(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 - 2) / 2;
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 - 1) / 2;
Comparable com = arrList[curPos];
while (curPos != 0) {
if (arrList[parentPos].compareTo(com) > 0)
break;
else {
arrList[curPos] = arrList[parentPos];
curPos = parentPos;
parentPos = (curPos - 1) / 2;
}
}
}
@SuppressWarnings("unchecked")
private void goDown(int i) {
int curPos = i;
int childPos = 2 * curPos + 1;
Comparable com = arrList[curPos];
while (childPos < heapSize) {
if ((childPos + 1 < 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 = 2 * 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((int) Math.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");
}
}