基本算法之堆排序

来源:互联网 发布:淘宝品牌调性分怎么查 编辑:程序博客网 时间:2024/05/17 00:17

堆排序

1、堆排序
什么是堆?堆是一种完全二叉树,并且满足每个结点的值都不小于或者不大于其左右结点的值。再简单的说就是利用大顶推或者小顶堆进行排序。堆排序基本思路:将待排序的序列构造成一个大顶堆,这时整个序列最大值就是根节点,将根节点与堆得末尾结点进行交换后,剩下的结点重新构成一个大顶堆,此时,次大值就是根节点,重复进行上面步骤,就可以得到一个有序序列。
2、代码实现

public static void heapSort(){int[] sort = { 68, 24, 91, 88, 6, 7, 5, 33, 10 }; int i;for(i = sort.length/2-1; i >= 0; i--){buildHeap(sort,i,sort.length);//调整为大顶堆}for (i = sort.length-1; i > 0; i--) {swap(sort,0,i);//交换buildHeap(sort,0,i);//重新构建大顶堆}for (int j = 0; j < sort.length; j++) {System.out.println(sort[j]);}}public static void buildHeap(int[] sort,int i,int n){int temp ,child = 0;for(temp = sort[i];(2*i+1) < n;i = child){child = 2*i+1;//左孩子索引if(child != n-1 && sort[child] < sort[child + 1])child++;if(temp < sort[child])sort[i] = sort[child];elsebreak;}sort[i] = temp;}public static void swap(int[] list,int i,int j){int temp = list[i];list[i] = list[j];list[j] = temp;}


3、小结:堆排序运行的时间主要消耗在构建堆上和重建堆得反复筛选。构建堆从完全二叉树的最底层最右边非叶子结点
开始,将他与其孩子结点进行比较和互换,构建堆得时间复杂度为 O(n) ,重建堆得时间复杂度为O(nlogn),所以平均时间
复杂度为O(nlogn)。堆排序性能远远高于简单排序、冒泡排序、直接插入排序时间复杂度的O(n²)。堆排序是一种不稳定
的排序。




原创粉丝点击