首页 > 代码库 > 算法-堆排序
算法-堆排序
package com.java.algorithm.test; import org.junit.Test; import java.util.Arrays; public class HeapSortTest { @Test public void testHeapSort() { int[] A = new int[]{4, 1, 3, 2, 16, 9, 10, 14, 8, 7}; this.heapSort(A); System.out.println(Arrays.toString(A)); } public int left(int i) { return 2 * i + 1; } public int right(int i) { return 2 * i + 2; } public void maxHeapify(int[] A, int i, int length) { int l = left(i); int r = right(i); int largetest = i; if (l < length && A[l] > A[i]) { largetest = l; } else { largetest = i; } if (r < length && A[r] > A[largetest]) { largetest = r; } if (largetest != i) { int temp = A[i]; A[i] = A[largetest]; A[largetest] = temp; this.maxHeapify(A, largetest, length); } } public void buildMaxHeap(int[] A) { int heapSize = A.length - 1; for (int i = heapSize / 2; i >= 0; i--) { this.maxHeapify(A, i, A.length); } } public void heapSort(int[] A) { int[] sortA = new int[A.length]; this.buildMaxHeap(A); for (int i = A.length - 1; i >= 1; i--) { int temp = A[0]; A[0] = A[i]; A[i] = temp; System.out.println(Arrays.toString(A)); this.maxHeapify(A, 0, i); } } }
本文出自 “宁静致远” 博客,请务必保留此出处http://woodpecker.blog.51cto.com/2349932/1954101
算法-堆排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。