算法很简单,堆存放在一个数组中,对数组实现递归堆排序,每次递归得出的最大值存在同一个数组的最后位置,J控制递归的次数和每次递归选出的值的存放位置。代码如下:
package String.Cheng;
public class heapSort {
public static int [] HeapSort(int [] a,int j){
int temp;
int [] b = new int [a.length];
for (int i = a.length-j; i >=0 ; i--) {
if (a[i]>a[i/2]) {
temp = a[i];
a[i] = a[i/2];
a[i/2] = temp;
}
}
temp = a[0];
a[0] = a[a.length-j];
a[a.length-j] = temp;
j++;
if(a.length-j>0)
HeapSort(a,j);
return a;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] a = {3,2,4,5,4,9,7,8};
int j = 1;
a = HeapSort(a,j);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]);
}
}
}