Question: HeapSort in Java. Can someone please help me modify or add code to this program where it creates a method with a parameter called Y
HeapSort in Java.
Can someone please help me modify or add code to this program where it creates a method with a parameter called Y which is used to provide unsorted integer list,and instead of sorting whole list, it only outputs Y sorted number of elements. I am not sure if constructor and method needs to be created but I would really appreciate some help.. Topic is HeapSort.
For example:
Given input 7 8 5 9 3 2 6 4 1 10 and y=4
The last four slots of the heap array would have: 7 8 9 10
The rest would not be completely sorted: 6 4 5 1 3 2 7 8 9 10
import java.util.Arrays;
public class Heap_Sort
{
public int array[];
public Heap_Sort(int[] array)
{
this.array = array;
}
public void makeHeap()
{
int temp;
int index;
for(int i=0;i { index= i; while (index != 0) { int parent = (index - 1) / 2; if (array[index] <= array[parent]) { break; } // swap child element to its parent one temp = array[index]; array[index] = array[parent]; array[parent] = temp; index = parent; } } } public void removekeys(int count) { int leftChild; int rightChild; int parentGreat; int temparray = array[0]; array[0] = array[count]; array[count] = temparray; int index = 0; count--; while (true) { leftChild=index*2+1; rightChild=index*2+2; // check the boundary if (rightChild > count) break; if (array[index] > array[leftChild] && array[index] > array[rightChild]) break; parentGreat= array[rightChild] > array[leftChild] ? rightChild : leftChild;// to get greater parent // swap current item to its parent one int temp = array[index]; array[index] = array[parentGreat]; array[parentGreat] = temp; index = parentGreat; } } public String heapSort() { makeHeap();//Calling Make heap Method for (int i=array.length-1;i>0;i--) { removekeys(i); } return Arrays.toString(array); } public static void main(String[] args) { int Array[]={7,8,5,9,3,2,6,4,1,10,11}; System.out.println("Before sorting Array Elements are:"+Arrays.toString( Array)); Heap_Sort obj=new Heap_Sort(Array); String SortedArray=obj.heapSort(); System.out.println(" The Sorted Array elemnts are:"+SortedArray); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
