java实现堆排序,思路参照算法导论

本文介绍了一种常用的排序算法——堆排序,并提供了详细的Java代码实现。通过构建最大堆并不断调整来实现数组元素的升序排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法一直是自己很弱的一环,最近争取有时间就投入上来。

直接贴上代码便于以后复习。


public class HeapSort {
public void heapAdjust(int[] heap,  int len, int p) {
int lchild = 2 * p;
int rchild = 2 * p + 1;
int largest = p;
if(lchild <= len && heap[largest] < heap[lchild]) {
largest = lchild;
}
if(rchild <= len && heap[largest] < heap[rchild]) {
largest = rchild;
}
if(largest != p) {
swap(heap, largest, p);
heapAdjust(heap, len, largest);
}
}


public void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}

public void buildHeap(int[] heap, int len) {
int p = len / 2;
for(int i = p; i >= 1; i--) {
heapAdjust(heap, len, i);
}
}

public void heapSort(int[] heap) {
int len = heap.length - 1;
buildHeap(heap, len);
for(int i = len; i >= 2; --i) {
swap(heap, i, 1);
heapAdjust(heap, i - 1, 1);
}

}

public static void main(String[] args) {
int[] a = {0, 18, 8, 5, 10, 6, 13, 14, 7, 5, 17};
HeapSort hs = new HeapSort();
hs.heapSort(a);
hs.pOut(a, a.length - 1);
}

public void pOut(int[] a, int k) {
for(int i = 1; i <= k; i++) {
System.out.print(a[i] + "  ");
}
System.out.println();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值