/*** 22.实现堆排序** */public class HeapSort{private static int[] a = null;public Test_22(int k){a = new int[k];for (int i = 0; i < a.length; i++){int temp = (int) (Math.random() * 100);System.out.print(temp + " ");a[i] = temp;}System.out.println();swap(a, 1, 2);System.out.println(Arrays.toString(a));}public static void main(String[] args){Test_22 test = new Test_22(22);test.deepsort(a, 0, 21);System.out.println(Arrays.toString(a));}private void deepsort(int[] a, int star, int end){// 1,建堆,大顶堆// 2.排队,即把堆顶大数移动到数组后面位置for (int i = 0; i < a.length - 1; i++){buildDeep(a, a.length - i);swap(a, 0, a.length - 1 - i);}}static private void buildDeep(int[] a, int length){// 堆的高度// 从尾巴开始比较,定义一个指针 指向最后的父亲节点// 首先,2个叶子比较,然后大的叶子和父亲节点比较,如果父亲大 则不操作 指针向前面走一位// 如果子节点比父亲大 父亲与子节点交换 指针指向该交换后的子节点位子// 當指針指向根位子的前一個位子 則退出循環int p = (length - 2) / 2;while (p >= 0){// 如果左子节点存在while (p * 2 + 1 < length){// 默认左子节点是最大的int max = p * 2 + 1;// 如果右子节点存在if ((p + 1) * 2 < length){// 比较左右子节点if (a[(p + 1) * 2] > a[max]){max = (p + 1) * 2;}}// 比较最大子节点与父亲节点if (a[p] < a[max]){// 最大子节点与父亲节点的值交换,并且指针p指向maxswap(a, max, p);p = max;} else{break;}}p--;}}/**** 数组中某2个位置的值交换** @param a* 数组* @param star* 待交换的第一个位子* @param end* 待交换的第二个位子* */private static void swap(int[] a, int star, int end){int temp = a[end];a[end] = a[star];a[star] = temp;}}
实现堆排序
最新推荐文章于 2024-12-30 20:13:45 发布
1076

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



