堆排序
package heapSort;
import java.util.Arrays;
public class HeapSort {
public static void main(String[] args) {
int[] a = {24, 10, 5, 1, 2, 24, 5};
heapSort(a);
System.out.println(Arrays.toString(a));
}
private static void heapSort(int[] a) {
for (int i = a.length/2 -1; i >= 0; i--) {
sortDownHeap(a,a.length-1,i);
}
for (int i = 0; i < a.length-1; i++) {
swap(a,0,a.length-1-i);
sortDownHeap(a,a.length - 2 -i ,0);
}
}
private static void sortDownHeap(int[] a, int high, int low) {
int k = low;
while(2*k + 1 <= high){
int bigIndex = 2*k+1;
if (bigIndex < high){
if (a[2*k+1] <a[2*k+2]){
bigIndex++;
}
}
if (a[bigIndex] > a[k]){
swap(a,k,bigIndex);
k = bigIndex;
}else{
break;
}
}
}
private static void swap(int[] a, int i, int j) {
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
|