JAVAは小根の並び替えを実現
1118 ワード
コード:
import java.util.Arrays;
public class solution {
public static void main(String []args){
int a[]={5,3,6,4,1,11,9,21,4,5,-5};
heapSort(a);
System.out.println(Arrays.toString(a));
}
public static void heapAdjust(int arr[],int start,int end){
int tem=arr[start];
for (int i=2*start+1;i<=end;i*=2){
if (iarr[i+1])
i++;
if (tem<=arr[i])
break;
arr[start]=arr[i];
arr[i]=tem;
start=i;
}
}
public static void heapSort(int []arr){
if (arr==null||arr.length==0)
return;
for(int i=arr.length/2;i>=0;i--)
heapAdjust(arr,i,arr.length-1);
System.out.println(arr[0]);
for (int i=arr.length-1 ;i>=0;i--){
swap(arr,0,i); //
heapAdjust(arr,0,i-1);
}
}
public static void swap(int arr[],int i,int j){
int t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}