码迷,mamicode.com
首页 > 编程语言 > 详细

java语言实现堆排序

时间:2016-11-09 20:00:35      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:int   string   ring   ++   pac   print   static   ext   and   

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

java语言实现堆排序

标签:int   string   ring   ++   pac   print   static   ext   and   

原文地址:http://www.cnblogs.com/ming-zi/p/6048120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!