标签:
1 package sorting; 2 3 /** 4 * 堆排序 5 * 平均O(nlogn),最好O(nlogn),最坏O(nlogn);空间复杂度O(1);不稳定;较复杂 6 * @author zeng 7 * 8 */ 9 public class DuiPaixu { 10 11 public static void duipaixu(int[] a) { 12 int i, tmp; 13 for (i = a.length / 2; i >= 1; i--) 14 HeapAdjust(a, i, a.length); 15 for (i = a.length; i > 1; i--) { 16 tmp = a[0]; 17 a[0] = a[i - 1]; 18 a[i - 1] = tmp; 19 HeapAdjust(a, 1, i - 1); 20 for (int j : a) 21 System.out.print(j + " "); 22 System.out.println(); 23 } 24 } 25 26 public static void HeapAdjust(int A[], int i, int length) { 27 int j = 2 * i; 28 int tmp = A[i - 1]; 29 while (j <= length) { 30 if (j < length && A[j - 1] < A[j]) 31 j++; 32 if (A[j - 1] > tmp) { 33 A[i - 1] = A[j - 1]; 34 i = j; 35 j = 2 * i; 36 } else { 37 break; 38 } 39 } 40 A[i - 1] = tmp; 41 } 42 43 public static void main(String[] args) { 44 int[] b = { 49, 38, 65, 97, 76, 13, 27, 50 }; 45 duipaixu(b); 46 for (int i : b) 47 System.out.print(i + " "); 48 49 } 50 51 }
标签:
原文地址:http://www.cnblogs.com/zengzhihua/p/4456745.html