import java.util.Arrays;
public class SortTest {
public static void main(String[] args) {
int[] a = {11,1,3,5,9,7,8,2,4,6,0,10};
// quickSort(a,0,a.length-1);
heapSort(a);
System.out.println(Arrays.toString(a));
}
public static void helpExch(int[] a,int i,int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
//Bubble Sort冒泡排序
public static void bubbleSort(int[] a){
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length-1;j++){
if(a[j]>a[j+1]){
helpExch(a,j,j+1);
}
}
}
}
//Quicksort 快速排序
public static void quickSort(int[] a,int s,int e){
if(s>=e) return;
int i = s;
int j = e;
int temp = a[j];
while(i<j){
while (i<j&&a[i]<temp) i++;
while (i<j&&a[j]>=temp) j--;
if(i<j) helpExch(a,i,j);
}
helpExch(a,e,j);
quickSort(a,s,j-1);
quickSort(a,j+1,e);
}
//Heapsort 堆排序
//堆排序
public static void heapSort(int[] a){
buildMaxHeap(a);
for(int i=a.length-1;i>0;i--){
helpExch(a, 0, i);
maxHeap(a,i,0);
}
}
//最大堆调整
private static void maxHeap(int[] a, int heapSize, int index) {
int left = 2*index + 1;
int right = 2*index +2;
int max = index;
if(left<heapSize&&a[max]<a[left]) max = left;
if(right<heapSize&&a[max]<a[right]) max = right;
if(max!=index){
helpExch(a, index, max);
maxHeap(a,heapSize,max);
}
}
//建立最大堆
private static void buildMaxHeap(int[] a) {
for(int i=a.length/2;i>0;i--){
maxHeap(a,a.length,i);
}
}
}