it is possible to make the heap sort algorithm more efficient by writing a method that will build a heap in place using
Posted: Mon Jul 11, 2022 9:49 am
it is possible to make the heap sort algorithm more efficient bywriting a method that will build a heap in place using the array tobe sorted. Implement such a method and rewrite the heap sortalgorithm to make use of it.
HeapSort.java
import jsjf.ArrayHeap;
/**
* HeapSort sorts a given array of Comparable objects usinga heap.
*
* @author Java Foundations
* @version 4.0
*/
public class HeapSort<T>
{
/**
* Sorts the specified array using a Heap
*
* @param data the data to be added to theheapsort
*/
public void heapSort(T[] data)
{
ArrayHeap<T> heap = newArrayHeap<T>();
// copy the array into a heap
for (int i = 0; i < data.length;i++)
heap.addElement(data);
// place the sorted elements backinto the array
int count = 0;
while (!(heap.isEmpty()))
{
data[count] =heap.removeMin();
count++;
}
}
}
HeapSort.java
import jsjf.ArrayHeap;
/**
* HeapSort sorts a given array of Comparable objects usinga heap.
*
* @author Java Foundations
* @version 4.0
*/
public class HeapSort<T>
{
/**
* Sorts the specified array using a Heap
*
* @param data the data to be added to theheapsort
*/
public void heapSort(T[] data)
{
ArrayHeap<T> heap = newArrayHeap<T>();
// copy the array into a heap
for (int i = 0; i < data.length;i++)
heap.addElement(data);
// place the sorted elements backinto the array
int count = 0;
while (!(heap.isEmpty()))
{
data[count] =heap.removeMin();
count++;
}
}
}