Question: This is Heap Sort Java Code. Please add comments on each line of codes to describe what doing import java.util.Arrays; public class HeapSort { static
This is Heap Sort Java Code. Please add comments on each line of codes to describe what doing
import java.util.Arrays; public class HeapSort { static void Exchange(int[] A, int x, int y) { int temp = A[x-1]; A[x-1] = A[y-1]; A[y-1] = temp; } public static void HeapSort(int[] A){ BuildMaxHeap(A); int heapSize = A.length; for(int i = A.length; i >= 2; i--){ Exchange(A,1,i); heapSize--; MaxHeapify(A,1,heapSize); } }
public static void BuildMaxHeap( int [] A){ for(int i = A.length/2;i>=1;i--) { MaxHeapify(A,i,A.length); } } public static void MaxHeapify(int [] A, int i,int heapSize){ int l = 2*i; int r = (2*i)+1; int largest; if (l <= heapSize && A[l-1] > A[i-1]) { largest = l; } else { largest = i; } if( r <=heapSize && A[r-1] > A[largest-1]){ largest = r; } if(largest != i) { Exchange(A, i, largest); MaxHeapify(A, largest, heapSize); } } public static void main(String[] args) { int[] random = new int[]{2, 9, -11, 8, 5, 9001, 3}; HeapSort(random); System.out.println("Expect random to be: -11, 2, 3, 5, 8, 9, 9001: " + Arrays.toString(random)); int[] LowtoHight = new int[]{2, 9, -11, 8, 5, 9001, 3}; HeapSort(LowtoHight); System.out.println("Expect LowtoHight to be: -11, 2, 3, 5, 8, 9, 9001: " + Arrays.toString(LowtoHight)); int[] HighttoLow = new int[]{9001, 9, 8, 5, 3, 2, -11}; HeapSort(HighttoLow); System.out.println("Expect HighttoLow to be: -11, 2, 3, 5, 8, 9, 9001: " + Arrays.toString(HighttoLow)); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
