第六章 堆排序
以后尽量能用迭代就别用递归啊,递归只是让自己轻松了,但是却增加了电脑的负担。
package chap06_Heap_Sort; import static org.junit.Assert.*; import java.util.Arrays; import org.junit.Test; public class SortAlorithms { /** * 返回当前下标下父节点的下标 * * @param i * @return */ protected static int parent(int i) { if (i == 0) return i; return (i - 1) / 2; } /** * 返回i的对应左子节点下标 * * @param i * @return */ protected static int left(int i) { return 2 * i + 1; } /** * 返回i对应右子节点下标 * * @param i * @return */ protected static int right(int i) { return 2 * (i + 1); } /** * 维护最大堆性质(递归方法实现) 容易内存溢出 * * @param a * @param i */ protected static void maxHeapify1(int[] a, int i, int SIZE) { int l = left(i); int r = right(i); int tmp; if (l < SIZE & r < SIZE) { if (a[i] >= a[l] & a[i] >= a[r]) return; else if (a[l] > a[r]) { tmp = a[i]; a[i] = a[l]; a[l] = tmp; i = l; } else { tmp = a[i]; a[i] = a[r]; a[r] = tmp; i = r; } } else if (l < SIZE) { if (a[i] < a[l]) { tmp = a[i]; a[i] = a[l]; a[l] = tmp; i = l; } } else { return; } maxHeapify1(a, i, SIZE); } /** * 重建最大堆,从i开始到size(不包含size索引) * * @param a * @param i * @param SIZE */ protected static void maxHeapify(int[] a, int i, int SIZE) { int l = left(i); int r = right(i); int tmp; while (l < SIZE & r < SIZE) { if (a[i] >= a[l] & a[i] >= a[r]) return; else if (a[l] > a[r]) { tmp = a[i]; a[i] = a[l]; a[l] = tmp; i = l; } else { tmp = a[i]; a[i] = a[r]; a[r] = tmp; i = r; } l = left(i); r = right(i); } if (l < SIZE) { if (a[i] < a[l]) { tmp = a[i]; a[i] = a[l]; a[l] = tmp; i = l; } } return; } /** * 将数组a转换成最大堆,不要用递归方法,尽量用迭代方法实现 * * @param a */ protected static void buildMaxHeap(int[] a) { int n = a.length; for (int i = n / 2; i >= 0; i--) { maxHeapify1(a, i, n); } } /** * 堆排序 * * @param n */ static void heapSort(int[] n) { buildMaxHeap(n); int l = n.length; int size = l; int tmp; for (int i = l - 1; i > 0; i--) { tmp = n[0]; n[0] = n[i]; n[i] = tmp; size--; maxHeapify(n, 0, size); } } @Test public void testName() throws Exception { // int[] a = { 2, 5, 3, 7, 8, 12, 0, 2, 45, 32 }; int[] a = { 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 }; // buildMaxHeap(a); // heapSort(a); maxHeapify1(a, 0, 10); System.out.println(Arrays.toString(a)); } }