如题,本文主要实现堆排序,主要展示大根堆的排序,代码如下:
说明:数组是从0~nums.length-1
import java.util.Iterator;
@SuppressWarnings("all")
public class HeapSort {
/**
* @param nums 所给数组
* @param n 数组长度
* @param i 需要调整的堆结点
*/
private void heapify(int[] nums, int n, int i) {
if(i>=n)
return ;
int lchild = 2 * i + 1; //左孩子
int rchild = 2 * i + 2; //右孩子
int max = i; //较大值下标
if(lchild < n && nums[lchild] > nums[max]) { //存在左孩子且左孩子的值大于当前最大值
max = lchild;
}
if (rchild < n && nums[rchild] > nums[max]) { //存在右孩子且右孩子的值大于当前最大值
max = rchild;
}
if(max != i) { //最大值下标不是原先值
swap(nums,max,i);
heapify(nums, n, max); //调整已调整的子结构的结构
}
}
/**
* @param nums 需构建成堆的数组
* @param n 数组长度
* @param i 起始坐标
*/
private void buildHeap(int[] nums, int n, int i) {
int lastNode = n - 1;
int parent = (lastNode - 1) / 2;
for (int j = parent; j >= i; j--) {
heapify(nums, n, j);
}
}
/**
* @param nums 进行堆排序的数组
* @param n 数组长度
*/
public void heap_sort(int[] nums, int n) {
buildHeap(nums, n, 0);
for (int i = n-1; i >= 0; i--) {
swap(nums, 0, i);
heapify(nums, i, 0);
}
}
private void swap(int[] nums, int max, int i) {
// TODO Auto-generated method stub
int temp = nums[max];
nums[max] = nums[i];
nums[i] = temp;
}
}
测试:
public class HeapTest {
public static void main(String[] args) {
int[] nums = { 2, 5, 3, 1, 10, 4};
HeapSort hSort = new HeapSort();
hSort.heap_sort(nums, 6);
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
}
}
结果展示:
推荐视频:
https://www.bilibili.com/video/BV1Eb41147dK?spm_id_from=333.337.search-card.all.click