An example of a JAVA algorithm starting with heap sort

  • 2020-04-01 02:52:48
  • OfStack

To learn heap sort, you first need to understand the concept of a heap, which is an array. Can be approximated as a complete binary tree array storage. But there's something else about it, which is that it's like a binary sort tree. There is a maximum heap and a minimum heap, the maximum heap means that the value of the root node is greater than the value of the child node, and the minimum heap means that the value of the root node is less than the value of the child node. Heap sort generally USES the maximum heap, while the minimum heap can construct priority queues. Inside a method is used to maintain the nature of the heap, or what we in the code below maxheap method, it is to maintain the mass of the nature of the method, the first parameter is the heap array, the second parameter is the adjustment of the exact location of the node may be the nature of the value of this node is not in conformity with the maximum heap, then this position is worth as a parameter, and the size is in pile the actual number of effective elements in the store. The length of the array may be the number of elements that are actually stored in the heap, but not all of the data needs to be built into the maximum heap. Said in the introduction to algorithms get left child node is 2 xi but we array starting from zero, so the left child node is xi + 1, 2 buildheap is build a maximum heap, the reason why we go to 2 per length is, the point of the child node is a leaf node, so we sort through from the bottom up to build a maximum heap. Ensures that all nodes in our heap satisfy the maximum heap property. Finally, heapsort is to take out the first node, heap sort the remaining nodes, and then take out the root node. This ensures that we get the maximum value every time we take it out.


public class HeapSort {
 private int getLeft(int i){
  return 2*i+1;
 }
 private int getRight(int i){
  return 2*i+2;
 }
 public void maxheap(int[] heap,int loc,int size){
  int l=getLeft(loc);
  int r=getRight(loc);
  int largest=loc;
  if(l<size&&heap[l]>heap[loc]){
   largest=l;
  }
  if (r<size&&heap[r]>heap[largest]) {
   largest=r;
  }
  if(largest!=loc){
   int cache=heap[loc];
   heap[loc]=heap[largest];
   heap[largest]=cache;
   maxheap(heap, largest, size);
  }
 }
 public void buildheap(int[] heap){
  for(int i=heap.length/2;i>=0;i--){
   maxheap(heap, i, heap.length);
  }
 }
 public void sort(int[] heap){
  buildheap(heap);
  for(int i=heap.length-1;i>1;i--){
   int cache=heap[0];
    heap[0]=heap[i];
    heap[i]=cache;
   maxheap(heap, 0,i );
  }
  int cache=heap[0];
   heap[0]=heap[1];
   heap[1]=cache;

 }
 public static void main(String[] args) {
  int[] heap=new int[]{4,1,5,3,7,12,65,7};
  HeapSort hs=new HeapSort();
  hs.sort(heap);
  for (int i = 0; i < heap.length; i++) {
   System.out.println(heap[i]);
  }
 }
}


Related articles: