堆排序
2017-05-26 20:19
204 查看
堆排序是建立在完全二叉树的基础上的。首先理解什么是大顶堆(小顶堆类似),堆顶不小于下面的左子树和右子树。
同理,左子树和右子树同样符合上述要求。
堆排序分为以下步骤:
1、堆初始化,即建立大顶堆,从最后一个大于1个节点的子树开始进行调整,直至调整至整个堆的堆顶为止;
2、将堆顶元素与新重建堆的最后一个节点互换;
3、除新重建堆的最后一个节点外,对堆顶元素进行调整,重建大顶堆;
4、重复步骤2、3至最后一个节点止;
结过上述步骤,待排序数组即为有序数组,实例如下:
同理,左子树和右子树同样符合上述要求。
堆排序分为以下步骤:
1、堆初始化,即建立大顶堆,从最后一个大于1个节点的子树开始进行调整,直至调整至整个堆的堆顶为止;
2、将堆顶元素与新重建堆的最后一个节点互换;
3、除新重建堆的最后一个节点外,对堆顶元素进行调整,重建大顶堆;
4、重复步骤2、3至最后一个节点止;
结过上述步骤,待排序数组即为有序数组,实例如下:
public class HeapSortMain { public static void main(String[] args) { int[] arr = {1,362,6,43,234,9,3,-45,2,5,1,9,2,6,7}; heapSort(arr); System.out.println(Arrays.toString(arr)); } //采用异或方式进行数据交换 static void change(int[] arr ,int index1,int index2){ arr[index1] ^= arr[index2]; arr[index2] ^= arr[index1]; arr[index1] ^= arr[index2]; } //一次堆调整,即重建大顶堆 static void heapShift(int[] arr,int start,int end){ int right = (start+1)<<1; int left = right-1; int maxIndex = start; if(left<=end && arr[maxIndex] < arr[left]) maxIndex= left; if(right<=end && arr[maxIndex] < arr[right]) maxIndex= right; if(maxIndex != start){ change(arr,maxIndex,start); heapShift(arr,maxIndex,end); } } //从最后一个大于1一个节点的子树的根开始,至整个树的根,建立完整的大顶堆 static void heapBuild(int[] arr){ int start = (arr.length-2)>>1; int end = arr.length-1; for(;start>=0;start--){ heapShift(arr,start,end); } } //堆排序 static void heapSort(int[] arr){ heapBuild(arr); //初始化建立大顶堆 for(int end=arr.length-1;end>0;end--){ change(arr,0,end); heapShift(arr,0,end-1); } } }
相关文章推荐
- Java基础篇之----排序(快速排序、冒泡排序、堆排序、简单选择排序、 希尔排序、直接插入排序)
- 可视化的排序三:选择排序和堆排序
- 堆与堆排序--递归与非递归java实现
- 算法笔记-堆排序
- 最大(小)堆和堆排序简介
- Java中PriorityQueue的排序,堆排序
- 堆排序
- 算法导论复习(3) 堆排序
- Algorithm Review 2 堆排序
- 堆排序
- 06_堆排序
- 优先队列和堆排序
- 排序算法C++ && Python实现---堆排序
- Kotlin练习-堆排序
- 小范围排序(堆排序)
- HeapSort(堆排序)
- java---插入排序,冒泡,归并,快速,希尔,堆排序
- 堆的应用----TopK问题和堆排序
- 堆排序
- 堆排序 C++实现