堆排序之-小顶堆

版权声明:本文为博主原创文章,欢迎大家转载,但是要注明我的文章地址。 https://blog.csdn.net/program_developer/article/details/83114201

不清楚堆概念的可以看这篇文章:堆排序之-大顶堆


用Java实现的小顶堆代码:

public class littleHeap {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = {3, 1, 6, 2, 9, 4, 5};
		heapSort(arr);
		for (int i : arr) {
			System.out.println(i);
		}
 	}
	
	public static void heapSort(int[] array) {
		//初始建堆
		for(int i=array.length/2-1; i>=0; i--) {
			adjustHeap(array, i, array.length);    //构建小顶堆
		}
		//堆排序
		for(int i=array.length-1; i>0; i--) {
			int temp = array[0];
			array[0] = array[i];
			array[i] = temp;
			adjustHeap(array, 0, i);
		}
	}
	
	public static void adjustHeap(int[] array, int i, int length) {
		int temp; //存放待调整的父节点
		int child;
		for(temp = array[i]; i*2 <= length-1; i = child) {
			child = i*2;
			if(child != (length-1) && array[child] > array[child+1])   //这一行代码和大顶堆有区别
				child++;                  //找出两个孩子中比较小的结点
			if(array[child] < temp)                                    //这一行代码和大顶堆有区别
				array[i] = array[child];
			else
				break;
		}
		array[i] = temp;
	}

}

猜你喜欢

转载自blog.csdn.net/program_developer/article/details/83114201