java 语言写的堆排序
import java.util.*;
/**
* @version 1.0 2016-10-20
* @author zhouxiaowu
*
*/
public class BigheapSort {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("please input some numbers");
String str = sc.nextLine();
String[] s = str.split("\\s+");
int[] num = new int[s.length];
for(int i=0;i<num.length;i++)
num[i]=Integer.parseInt(s[i]);
bigHeapSort(num);
for(int i:num)
System.out.print(i+" ");
}
public static void bigHeapSort(int[] num){//堆排序算法
int i;
buildBigHeap(num);
int temp;
for(i=num.length-1;i>=0;i--){
temp=num[0];
num[0]=num[i];
num[i]=temp;
bigHeapAdjust(num,0,i-1);
}
}
public static void buildBigHeap(int[] num){//建堆算法
for(int i=num.length/2;i>=0;i--)
bigHeapAdjust(num,i,num.length-1);
}
public static void bigHeapAdjust(int[] num,int low,int high){//调整堆算法
int temp = num[low];
int i=low;
int j=i;
i=2*i;
while(i<high){
if(i<high&&num[i]<num[i+1]) i++;
if(temp>=num[i]) break;
num[j]=num[i];
j=i;
i=i*2;
}
num[j]=temp;
}
}
测试结果:
Input :5 6 2 3 4 6
output :2 3 4 5 6 6
Input :6 5 12 7 3
output :3 5 6 7 12