您的位置:首页 > 其它

堆排序

2016-05-14 11:51 441 查看
public class Main{
public static void main(String[] args){
int[] A = {15,45,8,6,7};
int[] answer = heapSort(A);
System.out.println("answer:");
for(int i = 0; i < answer.length; ++ i) System.out.print(answer[i] + " ");
System.out.println("");
}

//keep the max_heap's features
public static void maxHeapify(int[] A,int i){
int largest = i;
int left = 2 * i;
int right = 2 * i + 1;
if(left < A.length && A[i] < A[left]) largest = left;
if(right < A.length && A[i] < A[right]) largest = right;
if(largest != i){
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
maxHeapify(A,largest);
}
}

//create a max_heap
public static void buildHeap(int[] A){
for(int i = A.length/2 - 1; i >= 0; --i)
maxHeapify(A,i);
}

//begin to sort
public static int[] heapSort(int[] A){
int[] answer = new int[A.length];
buildHeap(A);
for(int i = 0; i < A.length - 1; ++i){
answer[i] = A[0];
A[0] = A[A.length - 1 - i];
A[A.length - 1 - i] = -1000000000;
maxHeapify(A, 0);
}
answer[answer.length - 1] = A[0];
return answer;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: