您的位置:首页 > 编程语言 > Java开发

算法导论:堆排序(java实现)

2018-02-08 16:04 381 查看
import java.util.*;
public class Sort {
public static void main(String[] args) {
int[] a;
a = setArray();
heapsort(a);
for(int e:a)
System.out.print(e+" ");
}
public static int[] setArray() {
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
int[] a = new int
;
for(int i=0;i<a.length;i++) {
a[i] = in.nextInt();
}
return a;
}
public static int parent(int i) {
return i/2;
}
public static int left(int i) {
return 2*i;
}
public static int right(int i) {
return 2*i+1;
}
public static void max_heapify(int[] a,int i,int b) {
int l,r,largest;
l = left(i);
r = right(i);
if(l<=b&&a[l-1]>a[i-1])
largest = l;
else
largest = i;
if(r<=b&&a[r-1]>a[largest-1])
largest = r;
if(largest!=i) {
int temp;
temp = a[i-1];
a[i-1] = a[largest-1];
a[largest-1] = temp;
max_heapify(a,largest,b);
}
}
public static void build_max_heap(int[] a) {
int heap,j;
heap = a.length/2;
for(j=heap;j>=1;j--) {
max_heapify(a,j,a.length);
}
}
public static void heapsort(int[] a) {
int heap,temp;
heap = a.length;
build_max_heap(a);
for(int i=heap;i>=2;i--) {
temp = a[i-1];
a[i-1] = a[0];
a[0] = temp;
heap--;
max_heapify(a,1,heap);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 java 堆排序