堆排序(Heap-Sort)
来源:互联网 发布:怎么进入尼尔森数据网 编辑:程序博客网 时间:2024/06/06 01:22
堆排序(Heap-Sort)
(二叉)堆是一个数组,它可以被看成一颗近似的完全二叉树。树上的每个节点对应数组中一个元素。除了最底层外,该树是完全充满的,而且是从左向右填充的。堆排序是一种用堆来实现的排序算法,它的时间复杂度为O(nlgn),下面是堆排序的Java实现:
import java.util.Arrays;/** * Created by CvShrimp on 2017/10/11. */public class HeapSort { public static void maxHeap(int[] heap, int i, int endIndex) { int selfIndex = i - 1; int largest = selfIndex; int leftChildIndex = 2 * i - 1; int rightChildIndex = 2 * i; if(leftChildIndex <= endIndex && heap[leftChildIndex] > heap[selfIndex]) { largest = leftChildIndex; } if(rightChildIndex <= endIndex && heap[rightChildIndex] > heap[largest]) { largest = rightChildIndex; } if(largest != selfIndex) { swapHeapElement(heap, selfIndex, largest); maxHeap(heap, largest + 1, endIndex); } } public static void buildMaxHeap(int[] heap) { int startIndex = heap.length/2 - 1; for(int i = startIndex; i >= 0; i--) { maxHeap(heap, i + 1, heap.length - 1); } } public static void heapSort(int[] heap) { //构建最大堆,最大的元素在树的根节点 buildMaxHeap(heap); int maxIndex = heap.length - 1; for(int i = maxIndex; i >= 0;) { //最大的元素和最后一个元素互换位置 swapHeapElement(heap, 0, i); i--; //对剩下的前i+1个元素,再构建最大堆 maxHeap(heap, 1, i); } } public static void swapHeapElement(int[] heap, int i, int j) { int temp = heap[i]; heap[i] = heap[j]; heap[j] = temp; } public static void main(String[] args) { int[] heap = {1,5,6,3,4,10,7,66,666,66}; HeapSort.heapSort(heap); System.out.print("Sorted heap: "); System.out.print(Arrays.toString(heap)); }}
阅读全文
0 0
- 堆排序(heap sort)
- 堆排序(Heap Sort)
- 堆排序(Heap-Sort)
- 堆排序(heap sort)
- 堆排序(heap sort)
- 堆排序(Heap Sort)
- 堆排序(heap Sort)
- 堆排序(Heap Sort)
- 堆排序(heap sort)
- 堆排序(Heap Sort)
- 堆排序(Heap-Sort)
- Heap Sort(堆排序)
- 堆排序(Heap Sort)
- 堆排序(Heap Sort)
- 堆排序(Heap Sort)
- 堆排序 (Heap Sort)
- 堆排序(Heap Sort)
- heap sort 堆排序
- 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
- Python比较两个文件(txt,csv等)相同内容合并同一文件/文本时间大小比较大小
- CaptureWizPro(屏幕抓取软件)官方注册版V6.10下载 | CaptureWizPro 注册版
- Ubuntu14.04 ROS indigo 入门参考资料介绍
- 模糊PID控制算法的C++实现
- 堆排序(Heap-Sort)
- sdnu1053水题4
- HDU-5988 Coding Contest
- php伪静态地址
- 证明32位java对long和double的写操作不是原子性的
- 解决Notepad++ Plugin Manager无法加载插件的方法no new plugins available
- maven
- hdu 3926 瞎改改就过了。。。
- 事务的四个特性