java语言实现堆排序

package secondChapter;

import java.util.Random;

public class HeapSort {
    
    private static int AHeapSize;
    
    public static void main(String[] args) {
        
        HeapSort hs = new HeapSort();
        int[] A = new int[10];
        //产生随机数组
        for(int i=0;i<A.length;i++){
            A[i] = hs.generateRandomInt(50);
        }
        System.out.print("Original array:");
        for (int i = 0; i < A.length; i++) {
            System.out.print(A[i]+" ");
        }
        System.out.println();
        
        hs.heap_sort(A);
        
        System.out.print("Sorted array: ");
        for (int i = 0; i < A.length; i++) {
            System.out.print(A[i]+" ");
        }
    }
    
    //HEAPSORT过程
    public void heap_sort(int[] A) {
        AHeapSize = A.length;
        build_max_heap(A);
        
        System.out.print("build_max_heap: ");
        for (int i = 0; i < A.length; i++) {
            System.out.print(A[i]+" ");
        }
        System.out.println();
        
        
        for(int i=A.length;i>1;i--){
            int temp = A[0];
            A[0] = A[i-1];
            A[i-1] = temp;
            
            AHeapSize -= 1;
            max_heapify(A,1);
        }
    }
    
    //HUILD-MAX-HEAP过程
    public void build_max_heap(int[] A) {
        for(int i=A.length/2;i>0;i--){
            max_heapify(A,i);
        }
    }
    
    //MAX-HEAPIFY过程
    public void max_heapify(int[] A, int i) {    //i为 元素下标+1
        int l = 2*i;
        int r = 2*i+1;
        
        int largest;
        if(l<=AHeapSize && A[l-1]>A[i-1]){
            largest = l;
        }else{
            largest = i;
        }
        if(r<=AHeapSize && A[r-1]>A[largest-1]){
            largest = r;
        }
        if(largest!=i){
            int temp = A[i-1];
            A[i-1] = A[largest-1];
            A[largest-1] = temp;
            
            max_heapify(A, largest);
        }
    }
    
    private Random rd = new Random();
    public int generateRandomInt(int bound) {
        return rd.nextInt(bound);
    }
    
}

输出结果:

Original array:40 44 11 43 25 0 7 14 34 14
build_max_heap: 44 43 11 40 25 0 7 14 34 14
Sorted array: 0 7 11 14 14 25 34 40 43 44

转载于:https://www.cnblogs.com/ming-zi/p/6048120.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值