package com.tll.test; import java.util.Arrays; public class HeapSort { private int size = 0; int size() { return size; } public void heapfy(int[] queue){ for (int i = size/2; i >= 1; i--) { fixDown(queue,i); } } public void fixDown(int[] queue,int k){ int j; while ((j = k << 1) <= size && j > 0) { int less = j-1; if (j+1 <= size && queue[j-1] > queue[j]) { less = j; } if ( queue[less] < queue[k-1]) { change(queue,less,k-1); } k = j; } } public void fixUp(int[] queue,int k){ while (k > 1) { int j = k >> 1; if ( queue[j-1] > queue[k-1]) { change(queue,j-1,k-1); } k = j; } } public void change(int[] queue,int i,int j){ queue[i] ^= queue[j]; queue[j] ^= queue[i]; queue[i] ^= queue[j]; } public int getMin(int[] queue){ int integer = queue[0]; queue[0] =queue[size-1]; //queue[size-1] = null; size--; fixDown(queue,1); return integer; } public static void main(String[] args) { int[] queue =new int[]{ 9, 7,1, 5}; System.out.println(Arrays.toString(queue)); HeapSort heapSort = new HeapSort(); heapSort.size =queue.length; heapSort.heapfy(queue); System.out.println(Arrays.toString(queue)); for (int i = 0; i < queue.length; i++) { System.out.println(heapSort.getMin(queue)); } } }
[9, 7, 1, 5]
[1, 5, 9, 7]
1
5
7
9