Heap Sort
package org.bitcore.sort;
import org.bitcore.CoreUtil.SwapUtil;
public class HeapSort {
private int heapSize;
public void initialHeap(){
heapSize = 0;
}
public int maxHeapfy(int[] a,int i){
int l = 2*i+1;
int r = 2*(i+1);
int largest = i;
if( l <> a[i] )
largest = l;
if( r <> a[largest] )
largest = r;
if(largest != i){
SwapUtil.swap(a,largest,i);
maxHeapfy(a,largest);
}
return largest;
}
public void buildMaxHeap(int[] a){
heapSize = a.length;
for(int root=a.length/2-1;root>=0;root--){
maxHeapfy(a,root);
}
}
public void heapSort(int[] a){
buildMaxHeap(a);
for(int i = a.length-1;i>0;i--){
SwapUtil.swap(a,0,i);
heapSize = heapSize - 1;
maxHeapfy(a,0);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
HeapSort hp = new HeapSort();
hp.initialHeap();
int[] a = {4,1,3,2,16,9,10,14,8,7};
hp.heapSort(a);
for(int i = 0;i System.out.print("["+a[i]+"]\t");
}
}
}
import org.bitcore.CoreUtil.SwapUtil;
public class HeapSort {
private int heapSize;
public void initialHeap(){
heapSize = 0;
}
public int maxHeapfy(int[] a,int i){
int l = 2*i+1;
int r = 2*(i+1);
int largest = i;
if( l <> a[i] )
largest = l;
if( r <> a[largest] )
largest = r;
if(largest != i){
SwapUtil.swap(a,largest,i);
maxHeapfy(a,largest);
}
return largest;
}
public void buildMaxHeap(int[] a){
heapSize = a.length;
for(int root=a.length/2-1;root>=0;root--){
maxHeapfy(a,root);
}
}
public void heapSort(int[] a){
buildMaxHeap(a);
for(int i = a.length-1;i>0;i--){
SwapUtil.swap(a,0,i);
heapSize = heapSize - 1;
maxHeapfy(a,0);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
HeapSort hp = new HeapSort();
hp.initialHeap();
int[] a = {4,1,3,2,16,9,10,14,8,7};
hp.heapSort(a);
for(int i = 0;i System.out.print("["+a[i]+"]\t");
}
}
}
没有评论:
发表评论