package algorithm;
public class HeapSort {
public static int heap_size;
public static int parent(int i){
return i/2;
}
public static int rightChild(int i) {
// TODO Auto-generated method stub
return 2*i+1;
}
public static int leftChild(int i) {
// TODO Auto-generated method stub
return 2*i;
}
//与左右子树比较,找最大的arr[i]交换
public static void max_heapify(int[] arr, int i) {
// TODO Auto-generated method stub
int left = leftChild(i);
int right = rightChild(i);
int largest = 0;
if(left<heap_size&&arr[left]>arr[i]){
largest=left;
}else
largest = i;
if(right<heap_size&&arr[right]>arr[largest])
largest = right;
if(largest == i)
return;
else{
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
max_heapify(arr, largest);
}
}
//建一个大顶堆,在数据中,a.length/2+1一直到最后的元素都是叶子元素
public static void bulid_max_heap(int[] arr) {
// TODO Auto-generated method stub
for(int i=arr.length/2;i>=0;i--){
max_heapify(arr, i);
}
System.out.println("********初始堆***********");
for(int j=0;j<arr.length;j++)
System.out.print(arr[j]+" ");
System.out.println("\n*******************");
}
public static void heapSort(int[] arr) {
// TODO Auto-generated method stub
bulid_max_heap(arr);//建一个大顶堆
//看到网上有程序此处i>=2,与arr[1]做交换,不合适,应为数组从下班0开始存储
for(int i=arr.length-1;i>=1;i--){
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heap_size--;
max_heapify(arr,0);
}
}
public static void main(String[] args) {
int arr[] ={ 0,4, 1, 3, 2, 16, 9, 10,14, 8, 7};
heap_size = arr.length;
heapSort(arr);
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}
Java 堆排序的实现
最新推荐文章于 2024-04-07 14:04:06 发布