【牛客网】直通bat-面试算法精品课_第2章 排序 2.7 堆排序练习题(JAVA版)

来源:互联网 发布:如何评价蔡英文知乎 编辑:程序博客网 时间:2024/04/27 17:30

对于一个int数组,请编写一个堆排序算法,对数组元素排序。

给定一个int数组A及数组的大小n,请返回排序后的数组。

测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]

AC代码:
import java.util.*;public class HeapSort {    public int[] heapSort(int[] A, int n) {        // write code here        // 创建最大堆        for (int i=(n/2-1); i>=0; i--) {            //忽略叶子节点,从拥有叶子节点的下编号最大的节点开始,一直调整到根结点            MaxHeap(A, i, n);        }                for (int i=0; i<n-1; i++) {            // 把储存最大值的根结点调到数组尾部            swap(A, 0, n-1-i);            // 去掉尾节点,堆长度减1,调整最大堆,只需要重新调整根结点            MaxHeap(A, 0, n-1-i);        }                return A;    }        public void MaxHeap(int A[], int index, int len) {        // index为待调整节点,maxIndex为index的子节点; 若交换后子节点仍有其子节点,需要继续往下调整        for (int maxIndex=2*index+1; maxIndex<len; maxIndex=2*maxIndex+1) {            // 判断右孩子是否存在,且是否比左孩子大,选出最大孩子节点            if ((maxIndex+1)<len && A[maxIndex+1]>A[maxIndex]) {                maxIndex ++;            }            // 父与子节点数值判断            if (A[index] > A[maxIndex]) {                break;            } else {                swap(A, index, maxIndex);                index = maxIndex;            }        }    }        public void swap(int[] A, int i, int j) {        //不用开辟新内存        A[i] = A[i] + A[j];        A[j] = A[i] - A[j];        A[i] = A[i] - A[j];    }}










阅读全文
0 0
原创粉丝点击