Java Language! Code the Reheap Downward algorithm in a static method and code a
ID: 3767524 • Letter: J
Question
Java Language!
Code the Reheap Downward algorithm in a static method and code a driver program to demonstrate that it functions properly. The array to be built into a heap should be passed to the method. Then, modify the Reheap Downward method coded before so that the index of the root node of the tree and the size of the array are passed to the method as parameters: reheapDown(int [] array, int root, intsize). Provide a driver program to demonstrate that the method functions properly. In each case, output the contents of the array before and after the method is invoked. Also, code the Heap Sort algorithm and provide a driver program to demonstrate that it functions properly.
Explanation / Answer
ReheapDown Algorithm:-
Algorithm ReheapDown (heap, root, last)
1 if ((root*2 +1) <= last) (* There is at least left child *)
2 leftKey := heap[root*2 +1] (* left child value *)
3 rightChild := FALSE (* assume no right child)
1 if ((root*2 + 2) <= last) (* There is also right child *)
1 rightKey := heap[root*2 +2] (* right child value *)
2 rightChild := TRUE
2 end if
3 largeChildKey := leftKey;
4 largeChildIndex := root*2 + 1; (* assume left child larger *)
5 if (rightChild AND leftKey < rightKey)
1 largeChildKey := rightKey; (* right child exists and is larger *)
2 largeChildIndex := root*2 +2;
6 end if
7 if (heap[root] < largeChildKey) (* exchange larger child with root *)
1 hold := heap[root];
2 heap[root] := heap[largeChildIndex];
3 heap[largeChildIndex] := hold;
4 reheapDown (heap, largeChildIndex, last);
8 end if
2 end if
end ReheapDown
Java Code to Reheap Downward:
private void ReheapUp(int index)
{
bool Terminate;
int Processing = index;
do
{
Terminate = true;
if (Processing != 0)
{
int Parent = PARENT(Processing);
if (_Data[Processing].CompareTo(_Data[Parent]) > 0)
{
Utility.Swap(ref _Data[Parent], ref _Data[Processing]);
Terminate = false;
Processing = Parent;
}
}
} while (!Terminate);
}
private void ReheapDown(int index)
{
bool Terminate;
int Processing = index,
Largest = -1;
do
{
Terminate = true;
int LeftChild = CLEFT(Processing),
RightChild = CRIGHT(Processing);
if (LeftChild <= _LastUsed)
{
Largest = LeftChild;
if (RightChild <= _LastUsed && _Data[Largest].CompareTo(_Data[RightChild]) < 0)
Largest = RightChild;
if (_Data[index].CompareTo(_Data[Largest]) < 0)
{
Utility.Swap(ref _Data[Processing], ref _Data[Largest]);
Terminate = false;
Processing = Largest;
}
}
} while (!Terminate);
}
Java Program to Implement Heap Sort
*/
import java.util.Scanner;
/* Class HeapSort */
public class HeapSort
{
private static int N;
/* Sort Function */
public static void sort(int arr[])
{
heapify(arr);
for (int i = N; i > 0; i--)
{
swap(arr,0, i);
N = N-1;
maxheap(arr, 0);
}
}
/* Function to build a heap */
public static void heapify(int arr[])
{
N = arr.length-1;
for (int i = N/2; i >= 0; i--)
maxheap(arr, i);
}
/* Function to swap largest element in heap */
public static void maxheap(int arr[], int i)
{
int left = 2*i ;
int right = 2*i + 1;
int max = i;
if (left <= N && arr[left] > arr[i])
max = left;
if (right <= N && arr[right] > arr[max])
max = right;
if (max != i)
{
swap(arr, i, max);
maxheap(arr, max);
}
}
/* Function to swap two numbers in an array */
public static void swap(int arr[], int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/* Main method */
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Heap Sort Test ");
int n, i;
/* Accept number of elements */
System.out.println("Enter number of integer elements");
n = scan.nextInt();
/* Make array of n elements */
int arr[] = new int[ n ];
/* Accept elements */
System.out.println(" Enter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
/* Call method sort */
sort(arr);
/* Print sorted Array */
System.out.println(" Elements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
OUTPUT:
Enter number of integer elements
20
Enter 20 integer elements
57 205 342 200 197 946 631 92 66 581 345 220 398 249 329 87 186 144 462 431
Elements after sorting
57 66 87 92 144 186 197 200 205 220 249 329 342 345 398 431 462 581 631 946
Heap Sort Algorithm
Heap Sort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios. Heap sort algorithm is divided into two basic parts :
Creating a Heap of the unsorted list.
Then a sorted array is created by repeatedly removing the largest/smallest element from the heap, and inserting it into the array. The heap is reconstructed after each removal.
What is a Heap ?
Heap is a special tree-based data structure, that satisfies the following special heap properties :
Shape Property : Heap data structure is always a Complete Binary Tree, which means all levels of the tree are fully filled.
difference between complete and incomplete binary tree
Heap Property : All nodes are either [greater than or equal to] or [less than or equal to] each of its children. If the parent nodes are greater than their children, heap is called a Max-Heap, and if the parent nodes are smalled than their child nodes, heap is called Min-Heap.
How Heap Sort Works
Initially on receiving an unsorted list, the first step in heap sort is to create a Heap data structure(Max-Heap or Min-Heap). Once heap is built, the first element of the Heap is either largest or smallest(depending upon Max-Heap or Min-Heap), so we put the first element of the heap in our array. Then we again make heap using the remaining elements, to again pick the first element of the heap and put it into the array. We keep on doing the same repeatedly untill we have the complete sorted list in our array.
initially heapsort() function is called, which calls buildheap() to build heap, which inturn uses satisfyheap() to build the heap.
Complexity Analysis of Heap Sort:
Worst Case Time Complexity : O(n log n)
Best Case Time Complexity : O(n log n)
Average Time Complexity : O(n log n)
Space Complexity : O(n)
Heap sort is not a Stable sort, and requires a constant space for sorting a list. Heap Sort is very fast and is widely used for sorting.
Heap Sort:
Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.
What is Binary Heap?
Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible (Source Wikipedia)
A Binary Heap is a Complete Binary Tree where items are stored in a special order such that value in a parent node is greater(or smaller) than the values in its two children nodes. The former is called as max heap and the latter is called min heap. The heap can be represented by binary tree or array.
Why array based representation for Binary Heap?
Since a Binary Heap is a Complete Binary Tree, it can be easily represented as array and array based representation is space efficient. If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and right child by 2 * I + 2.
Heap Sort Algorithm for sorting in increasing order:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.
3. Repeat above steps until size of heap is greater than 1.
How to build the heap?
Heapify procedure can be applied to a node only if its children nodes are heapified. So the heapification must be performed in the bottom up order.
Lets understand with the help of an example:
Input data: 4, 10, 3, 5, 1
4(0)
/
10(1) 3(2)
/
5(3) 1(4)
The numbers in bracket represent the indices in the array
representation of data.
Applying heapify procedure to index 1:
4(0)
/
10(1) 3(2)
/
5(3) 1(4)
Applying heapify procedure to index 0:
10(0)
/
5(1) 3(2)
/
4(3) 1(4)
The heapify procedure calls itself recursively to build heap
in top down manner.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.