选择排序学过的有三种:简单选择排序、树形选择排序、堆排序
今天先来简单的了解一下堆排序:
完全二叉树,即从头到尾,从左到右依次排序,符合大堆(小堆)都行,即ki>=k2i && ki >= k2i+1
由于此处使用的是数组,则最长为array.length-1,并且 ki>=k2i+1 && ki >= k2i+2
下面的例子是百度上搜的,便于理解
实例如下:
public class MyHeap {public static void main(String[] args) {int[] array = {49,38,65,97,76,13,27,49 };print(array);HeapSort(array);print(array);}public static int[] HeapSort(int[] array){int n = (array.length-1)/2;for (int i = n; i >= 0; i--) {MaxHeap(array,i);}return array;}/**判断一个元素与其i*2+1(2)的关系*/public static int[] MaxHeap(int[] array,Integer i){int large = i;int index = 2*i+1;if(index< array.length && array[i]>array[index]){large = index;}index = 2*i +2;if(index< array.length && array[i]>array[index]){if( array[large]>array[index] ){large = index;}}if(large != i){int temp =array[i];array[i] = array[large];array[large] = temp;print(array);//每次交换顺序有打印if(large <= array.length/2){MaxHeap(array,large);//交换后,如果大的一层有下层,则再次判断大的一层是否符合}}return array;}/**打印数组*/public static void print(int[] array){for (int i = 0; i < array.length; i++) {System.out.print(array[i] + " ");}System.out.println();}
}