堆排序(JAVA)

来源:互联网 发布:asp购物网站源码 编辑:程序博客网 时间:2024/05/23 16:54

堆排序(Heapsort)是指利用堆积树(堆)这种数据结构所设计的一种排序算法,它是选择排序的一种。可以利用数组的特点快速定位指定索引的元素。堆分为大根堆和小根堆,是完全二叉树。大根堆的要求是每个节点的值都不大于其父节点的值,即A[PARENT[i]] >= A[i]。在数组的非降序排序中,需要使用的就是大根堆,因为根据大根堆的要求可知,最大的值一定在堆顶。

下面是我写的堆排序(Java版):

import java.util.Scanner;public class Main {// 堆排序建堆public static void heapSort(int[] array) {buildHeap(array);// 构建堆int n = array.length;int i = 0;for (i = n - 1; i >= 1; i--) {swap(array, 0, i);heapify(array, 0, i);}}public static void buildHeap(int[] array) {int n = array.length;// 数组中元素的个数for (int i = n / 2 - 1; i >= 0; i--)heapify(array, i, n);}public static void heapify(int[] A, int idx, int max) {int left = 2 * idx + 1;// 左孩子的下标(如果存在的话)int right = 2 * idx + 2;// 左孩子的下标(如果存在的话)int largest = 0;// 寻找3个节点中最大值节点的下标if (left < max && A[left] > A[idx])largest = left;elselargest = idx;if (right < max && A[right] > A[largest])largest = right;if (largest != idx) {swap(A, largest, idx);heapify(A, largest, max);}}public static void swap(int[] array, int i, int j) {int temp = 0;temp = array[i];array[i] = array[j];array[j] = temp;}public static void main(String[] args) {Scanner in = new Scanner(System.in);int n = in.nextInt();int[] p = new int[n];for (int i = 0; i < p.length; i++) {p[i] = in.nextInt();}heapSort(p);for (int i = 0; i < p.length; i++) {System.out.print(p[i] + " ");}}}

0 0
原创粉丝点击