堆排序代码实现
2017-04-20 18:28
288 查看
public class Main { public static void main(String[] args) { int [] m = {1,4,5,6,3,9,2,11,22}; new Main().heapSort(m); for(int i:m) System.out.println(i); } public void heapSort(int[] m){ for(int i=m.length-1;i>=0;i--){ HeapAdjust(m, i, m.length); } for(int i=m.length-1;i>0;i--){ int temp = m[i]; m[i] = m[0]; m[0] = temp; HeapAdjust(m, 0, i); } } /** * 建立初始堆 * @param array * @param parent 父节点 * @param length 长度 */ public void HeapAdjust(int[] array, int parent, int length){ int temp = array[parent]; // temp保存当前父节点 int child = 2 * parent + 1; // 先获得左孩子 while (child < length) { // 如果有右孩子结点,并且右孩子结点的值大于左孩子结点,则选取右孩子结点 if (child + 1 < length && array[child] < array[child + 1]) { child++; } // 如果父结点的值已经大于孩子结点的值,则直接结束 if (temp >= array[child]) break; // 把孩子结点的值赋给父结点 array[parent] = array[child]; // 选取孩子结点的左孩子结点,继续向下筛选 parent = child; child = 2 * child + 1; } array[parent] = temp; } }
相关文章推荐
- 选择排序、树形排序、堆排序的java代码实现
- C语言对堆排序一个算法思路和实现代码
- 算法-java代码实现堆排序
- 算法代码实现之堆排序,Java实现
- HeapSort堆排序Java实现图文代码详解
- 排序法系列之六---堆排序(C++代码实现)
- 快速排序,归并排序,堆排序的java代码实现
- 算法代码实现之堆排序,C/C++实现
- 堆排序 完整代码与详细注释 C++语言实现
- 深入解析堆排序的算法思想及Java代码的实现演示
- 堆排序的代码实现 - 数据结构和算法93
- 算法代码实现之堆排序,Golang(Go语言)实现
- 排序基础之归并排序、快排、堆排序、希尔排序思路讲解与Java代码实现
- 创建堆,堆排序的详细实现过程,C++完整代码
- 插入排序、冒泡排序、选择排序、希尔排序、快速排序、归并排序、堆排序和LST基数排序的C++代码实现
- 堆与堆排序原理及代码实现
- Java实现堆排序(Heapsort)实例代码
- 选择排序——简单选择排序和堆排序,C++代码实现
- 【数据结构与算法】【排序】堆排序的代码实现