Sorting algorithm -heapranking

heapranking principle

heapranking-Java Code

public  class heapranking {
     public  static  void main (String [] args) { 
        Scanner in = new new Scanner (the System.in);         
        System.out.println ( "Please enter the size of the array" );        
         int N = in.nextInt (); // read the size of the array from the keyboard.        
        Double A [] = new new  Double [N];         
        System.out.println ( "Please enter the number of array" );        
         for ( int I = 0; I <N; I ++) { // a read input from the keyboard number.            
            A [I] = in.nextDouble (); 
        }
        //a sample input
        System.out.println("Input: " + Arrays.toString(A));
        heapranking maxhp = new heapranking();
        maxhp.heapsort(A);
        System.out.println("Output: " + Arrays.toString(A));
    }
    protected double A[];
    protected int heapsize;
    protected int parent(int i) {return (i - 1) / 2;}
    protected int left(int i) {return 2 * i + 1;}
    protected int right(int i) {return 2 * i + 2;}

    //constructors
    public heapranking(){}
    public heapranking(double A[]){
        buildMaxHeap(A);
    }    

    protected void maxHeapify(int i){
        int l = left(i);
        int r = right(i);
        int largest = i;
        if (l <= heapsize - 1 && A[l] > A[i])
            largest = l;
        if (r <= heapsize - 1 && A[r] > A[largest])
            largest = r;
        if (largest != i) {
            double temp = A[i];
            // swap
            A[i] = A[largest];
            A[largest] = temp;
            this.maxHeapify(largest);
        }
    }
    
    public void buildMaxHeap(double [] A){
        this.A = A;
        this.heapsize = A.length;
        
        for (int i = parent(heapsize - 1); i >= 0; i--)
            maxHeapify(i);        
    }
    
    public void heapsort(double [] A){
        buildMaxHeap(A);
        
//        int step = 1;
        for (int i = A.length - 1; i > 0; i--) {
            double temp = A[i];
            A[i] = A[0];
            A[0] = temp;
            heapsize--;
//            System.out.println("Step: " + (step++) + Arrays.toString(A));
            maxHeapify(0);
        }        
    }
}

 

Guess you like

Origin www.cnblogs.com/jocelynD-9/p/11262636.html