/**
* Implement heapSort
* @author gtowell
* created: April 15, 2020
*/
public class Heap extends SortBase{
/**
* Insert into an array organized as a heap.
* While this code is correct, it is also a very simplified version of a heap,
* in that the heap contains only a key and the key must be an integer.
* @param heap the array
* @param size the number of data items in the array
* @param dta the data item to be added
*/
private void heapInsert(int[] heap, int size, int dta)
{
// put in at end
int loc = size;
heap[loc] = dta;
// bubble up
int upp = (loc-1)/2;
while (loc>0)
{
if (heap[loc] > heap[upp])
{
// swap and climb
int tmp = heap[upp];
heap[upp] = heap[loc];
heap[loc] = tmp;
loc = upp;
upp = (loc-1)/2;
}
else
{
break;
}
}
}
/**
* Remove the top element of the heap.
* While this code is correct, it is also a very simplified version of a heap,
* in that the heap contains only a key and the key must be an integer.
* @param heap an array whiose data is organized as a heap
* @param heapSize the number of data items in the heap
* @return the top most item in the heap.
*/
private int heapPoll(int[] heap, int heapSize)
{
if (heapSize==0)
return -1;
int rval=heap[0];
heap[0]=heap[heapSize-1];
heap[heapSize-1]=-1;
downheap(heap, 0, heapSize);
return rval;
}
/**
* Move an item downward in the heap
* @param heap array containing the heap
* @param upp the location of the item in the heap
* @param heapSize the number of items in the heap
*/
private void downheap(int[] heap, int upp, int heapSize)
{
while (true)
{
int dwn;
int dwn1 = upp*2+1;
if (dwn1>=heapSize)
break;
int dwn2 = upp*2+2;
if (dwn2>=heapSize)
{
dwn=dwn1;
}
else
{
if (heap[dwn1]>heap[dwn2])
dwn=dwn1;
else
dwn=dwn2;
}
if (heap[dwn]>heap[upp])
{
int tmp = heap[dwn];
heap[dwn] = heap[upp];
heap[upp]=tmp;
upp=dwn;
}
else
{
break;
}
}
}
/**
* Build heap from top down
*
* @param rdm the data to put into the heap
*/
public void heapsort1(int[] rdm)
{
int[] newheap = new int[rdm.length];
for (int i=0; i=0)
{
int fullStart=i-1;
int fullLen=i;
for (int j=0; j