JAVA数据结构与算法之————堆排序
直接上代码:
public class Heap {
public void heapSort(int[] heap){
/*从最后一个叶子节点的父节点往前调整堆,直到根节点*/
for(int i = (heap.length - 1) / 2; i > 0; i--){
heapAdjust(heap, i, heap.length - 1);
}
/*输出根节点,然后将根节点与最后一个叶子节点交换,然后只要调整根节点,使二叉树重新变成堆*/
for(int i = heap.length - 1; i > 0; i-- ){
System.out.print(heap[1] + " ");
swap(heap, 1, i);
heapAdjust(heap, 1, i - 1);
}
}
/*调整二叉树*/
private void heapAdjust(int[] heap, int s, int m){
/*s为待调整的子树的根节点,m为二叉树的最后一个元素*/
int temp = heap[s];
/*i = 2 * s 使i指向待排序节点的左子树*/
for(int i = 2 * s; i <= m; i = i * 2){
/*i指向左右子树中最大的一个*/
if(i < m && heap[i] < heap[i + 1]){
i++;
}
if(temp > heap[i]){
break;
}
/*最大的子节点赋值给父节点*/
heap[s] = heap[i];
/*s指向最大的父节点*/
s = i;
}
heap[s] = temp;
}
public void swap(int[] heap, int i, int j){
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
public static void main(String[] args) {
Heap heap = new Heap();
int[] data = {3, 4, 1, 7, 9, 11, 4, 5};
heap.heapSort(data);
}
}