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[n];
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实现)
最新推荐文章于 2024-12-30 20:13:45 发布
本文介绍了一个使用Java实现的堆排序算法。该算法首先通过构建最大堆来组织输入数组,然后通过重复移除最大元素并重新调整堆来完成排序过程。文章提供了一个完整的Java程序示例,包括读取用户输入、构建堆、执行排序以及输出排序后的数组。
&spm=1001.2101.3001.5002&articleId=79290781&d=1&t=3&u=2d7c8fb75b934230a59cfc15e93f025e)
3911

被折叠的 条评论
为什么被折叠?



