记录一下堆排序的代码。如果了解原理,看代码应该也能看懂。如果不了解,点击 ,查看大佬博客。
这里是升序
步骤:
(1)将数据进行简单的数上浮。
(2)
(a)然后每次将堆顶的数(最大值)和数组最后一个数进行交换(已经交换过之后,就不用再理睬了,下一次就和倒数第二个交换,依次。。。这样每一次下来就会有一个数确定最终位置。
(b)当交换之后,堆顶的数字可能不是最大值了,所以需要再次进行数据的上浮(当然不包括已经确定位置的数)。
代码:代码还可以优化,将两个构造大顶堆的方法合并。
代码参考自
package tree;
import java.util.Scanner;
public class HeapSort {
static int [] A;
//堆排序(升序)
public static void heapSort( int []A ) {
//构造大顶堆
heapInsert(A);
int length = A.length;
while( length > 1 ) {
swap( A , 0 , length - 1 );
length--;//每次交换都能将一个最大值放在最后面
//构造大顶堆
heapify( A, 0, length );
}
}
//构造大顶堆
public static void heapInsert( int [] A ) {
for( int i = 0 ; i < A.length ; i ++ ) {
//当前插入的索引
int currentIndex = i;
//父节点索引
int fatherIndex = ( currentIndex - 1 ) / 2 ;
//如果当前结点大于父节点,则与之交换,直到不大于
while( A[ currentIndex ] > A[ fatherIndex ] ) {
//交换当前结点与父结点的值
swap( A , currentIndex ,fatherIndex );
//将当前索引指向父结结点
currentIndex = fatherIndex;
fatherIndex = ( currentIndex - 1 ) / 2;
}
}
}
//将剩余的数构造成大顶堆(通过顶端的数下降)
public static void heapify( int [] A , int index , int size ) {
//这里的size是用来不影响已经确定最终位置的数
int left = 2 * index + 1;
int right = 2 * index + 2;
while( left < size ) {
int largestindex;
//判断孩子中较大的值索引(要确保右孩子size范围之内)
if( A[left] < A[right] && right < size ) {
largestindex = right;
}
else {
largestindex = left;
}
//比较父结点的值与孩子中较大的值,并且确定最大值的索引
if( A[index] > A[largestindex] ) {
largestindex = index;
}
//如果父结点索引是最大值的索引,那已经是大顶堆了,则退出循环
if( index == largestindex ) {
break;
}
//父节点不是最大值,与孩子中较大值交换
swap( A , largestindex , index);
//将索引指向孩子中较大的值的索引
index = largestindex;
//重新计算交换之后的孩子的索引
left = 2 * index + 1;
right = 2 * index + 2;
}
}
//交换函数,将两个数进行值的交换
public static void swap( int [] A , int i , int j ) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
public static void main(String[] args) {
int [] A = { -1, 9, 9, 9, 1, 9, 8, 7, 3, 4 , 2 };
heapSort(A);
for( int i = 0 ; i < A.length ; i ++ ) {
System.out.print( A[i] + " " );
}
}
}
来自力扣的一份代码
public int [] heapSort(int[] nums) {
int heapSize = nums.length;
buildMaxHeap(nums, heapSize);
for (int i = nums.length - 1; i >= 0; --i) {
swap(nums, 0, i);
--heapSize;
maxHeapify(nums, 0, heapSize);
}
return nums;
}
public void buildMaxHeap(int[] a, int heapSize) {
for (int i = heapSize / 2; i >= 0; --i) {
maxHeapify(a, i, heapSize);
}
}
public void maxHeapify(int[] a, int i, int heapSize) {
int l = i * 2 + 1, r = i * 2 + 2, largest = i;
if (l < heapSize && a[l] > a[largest]) {
largest = l;
}
if (r < heapSize && a[r] > a[largest]) {
largest = r;
}
if (largest != i) {
swap(a, i, largest);
maxHeapify(a, largest, heapSize);
}
}
public void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}