java算法----排序----(7)堆排序
1 package log; 2 3 import java.util.Arrays; 4 5 public class Test4 { 6 /** 7 * 堆排序 8 * 9 * @param args 10 */ 11 public static void main(String[] args) { 12 int arr[] = { 49, 20, 36, 51, 18, 94, 61, 31, 50 }; 13 14 // 循环输出该数组内容 15 System.out.println("排序之前:"); 16 for (int a : arr) { 17 System.out.print(a + "\t"); 18 } 19 System.out.println(); 20 21 int arrlength = arr.length; 22 23 // 循环建堆 24 for (int i = 0; i < arrlength - 1; i++) { 25 build(arr, arrlength - 1 - i); 26 swap(arr, 0, arrlength - 1 - i); 27 System.out.println(Arrays.toString(arr)); 28 } 29 30 // 循环输出该数组内容 31 System.out.println("排序之后:"); 32 for (int a : arr) { 33 System.out.print(a + "\t"); 34 } 35 System.out.println(); 36 37 } 38 39 private static void build(int[] data, int lastIndex) { 40 for (int i = (lastIndex - 1) / 2; i >= 0; i--) { 41 int k = i; 42 while (k * 2 + 1 <= lastIndex) { 43 int bigIndex = 2 * k + 1; 44 if (bigIndex < lastIndex) { 45 if (data[bigIndex] < data[bigIndex + 1]) { 46 bigIndex++; 47 } 48 } 49 50 if (data[k] < data[bigIndex]) { 51 swap(data, k, bigIndex); 52 k = bigIndex; 53 } else { 54 break; 55 } 56 57 } 58 } 59 } 60 61 private static void swap(int[] data, int i, int j) { 62 int temp = data[i]; 63 data[i] = data[j]; 64 data[j] = temp; 65 } 66 67 }
下面是控制台的输出
llh