SlideShare a Scribd company logo
1 of 3
Download to read offline
Complete the classes shown below: 1. The MinHeap Class Write necessary code in the method
buildMinHeap, downHeap and upHeap. Add your necessary changes in the section where this
block of code is written: /*** *** Write YOUR CODE HERE *** ***/ The driver generates a
Sorted List of decreasing order using HeapSort after the specified heap operations are performed.
The details of these methods are given below, also additional hints are provided in the code as
comments. Also we have added helper methods for generating output. Do not edit any helper
methods, they are necessary for Gradescope. Complete the code before the due date. Submit the
completed MinHeap.java file via Gradescope module in folio. Details of Methods:
buildMinHeap: Given an array of N elements, stored from indices 1 thru N, build a min-heap
using bottom-up construction. The helper functions in the DriverPA2.java file read the size and
populate the input array before calling on your buildMinHeap operation. downHeap: downHeap
is an operation that is used to maintain the heap property after removing the root node from a
heap. When the root node is removed, the last node in the heap is moved to the root position, and
the downHeap operation is applied to this node to restore the heap property During downHeap,
the node is compared with its children, and if its value is greater than the value of its children , it
is swapped with the child that has the lowest value. This process is repeated until the heap
property is restored. downHeap will restore the heap-order property by swapping key k along a
downward path from the root. You need to maintain the Min Heap properties within the reduced
size of the array. upHeap: upHeap is an operation that is used to maintain the heap property after
inserting a new node into the heap. When a new node is inserted, it is placed at the bottom of the
heap and the upHeap operation is applied to this node to restore the heap property. During
upHeap, the node is compared with its parent, and if its value is less than the value of its parent ,
it is swapped with its parent. This process is repeated until the heap property is restored. upHeap
will restore the heap-order property by swapping k along an upward path from the insertion
node. During each insertion process, you need to ensure the MinHeap property is maintained.
Input File Structure: Example: minheap0.txt 7 // Input array size(size_n) 21 16 13 12 9 7 3 //
Input Array for MinHeap build (int[] minHeap) 10 30 20 5 15 // Integer array to be inserted in
the MinHeap(int[] newelements) Sample Output in DriverPA2: Result after buildheap: 3 9 7 12
16 21 13 Removed Elements: 3 7 9 12 13 HeapSort result: 30 21 20 16 15 10 5 We have added 5
more input files, you can test them as well changing the file name in the Driver.java main
method. These are the files: minheap1.txt minheap2.txt minheap3.txt minheap4.txt minheap5.txt
Additional Notes: We have allocated the size of the Input Array more than enough capacity for
convenience. The printMinHeapArray method prints the minHeap array content to the size
specified. package assignment; public class MinHeap { static int[] minHeap; static int size_n; /**
* Helper functions * MinHeapOperations will evaluate three operations: buildMinHeap,
downHeap & upHeap * Parameters: * input: Integers from the Second line of input text *
newelements: Integers from the Third line of input text * size: Input array size from the First line
of input text * The operations to be implemented: * 1. buildMinHeap: Build the MinHeap * 2.
downHeap: Algorithm downheap restores the heap-order property by swapping key k along a
downward path from the root. * 3. upHeap: The upheap process is used to add a node to a heap
while maintaining the Heap property. * heapSort and printMinHeapArray helper functions are
added for generating the desired output. */ public String[] MinHeapOperations(int[] input, int[]
newelements, int size) { // Assigning/Initiating the class static members minHeap =
input.clone(); size_n = size; // These two variables are needed for Gradescope evaluation String[]
results = new String[3]; String removedElements = ""; buildMinHeap(minHeap, size_n);
results[0] = printMinHeapArray(minHeap, size_n); System.out.println("Result after buildheap: "
+ results[0]); //Remove 5 minimum numbers from the MinHeap one by one. for(int i = 0; i < 5;
i++) { removedElements = removedElements + removeMin(minHeap) + " "; } results[1] =
removedElements.trim(); System.out.println("Removed Elements: " + results[1]); //Insert the
Elements from the newelements one by one. for (int i = 0; i < newelements.length; i++) {
insert(minHeap, newelements[i]); } results[2] = heapSort(minHeap, size_n);
System.out.println("HeapSort result: " + results[2]); return results; } // Helper function /* A
utility function for heapSort operation */ static String heapSort(int array[], int n) { // One by one
extract an element from heap for (int i = n; i > 0; i--) { // Move current root to end int temp =
array[1]; array[1] = array[i]; array[i] = temp; downHeap(array, 1, i-1); } return
printMinHeapArray(array, n); } // Helper function /* A utility function to print array of size n */
static String printMinHeapArray(int arr[], int n) { String result = ""; for (int i = 1; i <= n; ++i)
result = result + arr[i] + " "; return result.trim(); } /** * Helper function * Remove the
minimum/smallest elements from the MinHeap * During each removal process, ensure the
MinHeap property. * minHeap array gets updated during this process */ public static int
removeMin(int[] array) { int popped = array[1]; array[1] = array[size_n]; size_n--;
downHeap(array, 1, size_n); return popped; } /* * Helper function * Insert the elements one by
one in the MinHeap * Store the new item at the last empty cell in the array * minHeap array gets
updated during this process */ public static void insert(int[] array, int newelement) { size_n++;
int current = size_n; array[current] = newelement; upHeap(array, size_n); } /** * Build the
MinHeap * minHeap array gets updated during this process */ public static void
buildMinHeap(int[] array, int size) { /*** *** Write YOUR CODE HERE *** ***/ } /** * After
replacing the root key with the key of the last node, the heap-order property may be violated *
downHeap restores the heap-order property by swapping key k along a downward path from the
node at given index */ public static void downHeap(int arr[], int index, int size) { /*** *** Write
YOUR CODE HERE *** ***/ } /** * During each insertion process, ensure the MinHeap
property. * After the insertion of a new element, the heap-order property may be violated.
upHeap restores the heap-order property by swapping k along an upward path from the insertion
node */ public static void upHeap(int[] array, int size) { /*** *** Write YOUR CODE HERE
*** ***/ } } Driver PA2 should not be edited. package assignment; import java.io.File; import
java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import
java.util.Scanner; public class DriverPA2 { private static int size; static int[] inputArray; // Array
elements to be modified and for generating MinHeap static int[] newElementsArray; // New
elements to be inserted in the Heap // Helper functions static void
prepareInputDataFromText(String filename) throws FileNotFoundException, IOException{ File
file = new File(filename); Scanner sc = new Scanner(file); String size_n = sc.nextLine(); size =
Integer.parseInt(size_n); // Allocating the array for convenience inputArray = new int[2*size +
10]; String input = sc.nextLine(); String[] strs = input.trim().split("s+");
StringArrToIntArr(inputArray, strs, 1); input = sc.nextLine(); strs = input.trim().split("s+");
newElementsArray = new int[strs.length]; StringArrToIntArr(newElementsArray, strs, 0);
sc.close(); } // Helper functions to populate array according to the need public static void
StringArrToIntArr(int[] arr, String[] s, int startingindex) { //startingindex is the index from where
we are populating the array from input file for (int i = 0, j = startingindex; i < s.length; i++, j++)
{ arr[j] = Integer.parseInt(s[i]); } } public static void main(String[] arg) throws
FileNotFoundException, IOException{ // Read the file and generate output // Change the
filename according to your need for testing purpose String fileName = "minheap0.txt";
prepareInputDataFromText(fileName); MinHeap minHeapObj = new MinHeap(); // This result
will be evaluated in Gradescope String[] generatedResults =
minHeapObj.MinHeapOperations(inputArray, newElementsArray, size); } } Test with Driver
and .txt file minheap0.txt which contains 7 21 16 13 12 9 7 3 10 30 20 5 15

More Related Content

Similar to Complete the classes shown below 1. The MinHeap Class Write necessa.pdf

Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
info114
 
Educational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdfEducational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdf
rajeshjangid1865
 
Files that you must write and turn in Please do not turn in.pdf
Files that you must write and turn in Please do not turn in.pdfFiles that you must write and turn in Please do not turn in.pdf
Files that you must write and turn in Please do not turn in.pdf
actocomputer
 
You must implement the following functions- Name the functions exactly.docx
You must implement the following functions- Name the functions exactly.docxYou must implement the following functions- Name the functions exactly.docx
You must implement the following functions- Name the functions exactly.docx
Sebastian6SWSlaterb
 
in c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdfin c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdf
stopgolook
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
fashiongallery1
 
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdfEverything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdf
firstchoiceajmer
 
please help implement the following in C. below are instructions and.pdf
please help implement the following in C. below are instructions and.pdfplease help implement the following in C. below are instructions and.pdf
please help implement the following in C. below are instructions and.pdf
amarrex323
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
eyebolloptics
 
Objectives 1. using indirect addressing 2. passing parameters.pdf
Objectives 1. using indirect addressing 2. passing parameters.pdfObjectives 1. using indirect addressing 2. passing parameters.pdf
Objectives 1. using indirect addressing 2. passing parameters.pdf
fcsondhiindia
 
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docxLab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
DIPESH30
 

Similar to Complete the classes shown below 1. The MinHeap Class Write necessa.pdf (20)

Priority queue
Priority queuePriority queue
Priority queue
 
2.0 Stacks.pptx
2.0 Stacks.pptx2.0 Stacks.pptx
2.0 Stacks.pptx
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
 
Educational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdfEducational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdf
 
Files that you must write and turn in Please do not turn in.pdf
Files that you must write and turn in Please do not turn in.pdfFiles that you must write and turn in Please do not turn in.pdf
Files that you must write and turn in Please do not turn in.pdf
 
You must implement the following functions- Name the functions exactly.docx
You must implement the following functions- Name the functions exactly.docxYou must implement the following functions- Name the functions exactly.docx
You must implement the following functions- Name the functions exactly.docx
 
Cambio de bases
Cambio de basesCambio de bases
Cambio de bases
 
in c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdfin c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdf
 
Stacks
StacksStacks
Stacks
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
 
Heap Tree.pdf
Heap Tree.pdfHeap Tree.pdf
Heap Tree.pdf
 
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdfEverything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdf
 
Find attached the code to implement the following two functions- 1- In.pdf
Find attached the code to implement the following two functions- 1- In.pdfFind attached the code to implement the following two functions- 1- In.pdf
Find attached the code to implement the following two functions- 1- In.pdf
 
Hadoop Installation_13_09_2022(1).docx
Hadoop Installation_13_09_2022(1).docxHadoop Installation_13_09_2022(1).docx
Hadoop Installation_13_09_2022(1).docx
 
please help implement the following in C. below are instructions and.pdf
please help implement the following in C. below are instructions and.pdfplease help implement the following in C. below are instructions and.pdf
please help implement the following in C. below are instructions and.pdf
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
Objectives 1. using indirect addressing 2. passing parameters.pdf
Objectives 1. using indirect addressing 2. passing parameters.pdfObjectives 1. using indirect addressing 2. passing parameters.pdf
Objectives 1. using indirect addressing 2. passing parameters.pdf
 
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docxLab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
 

More from americanopticalscbe

My private pilot training took place in 1977 in a Cessna 150 from Rya.pdf
 My private pilot training took place in 1977 in a Cessna 150 from Rya.pdf My private pilot training took place in 1977 in a Cessna 150 from Rya.pdf
My private pilot training took place in 1977 in a Cessna 150 from Rya.pdf
americanopticalscbe
 
Mycocepurus ant and social parasite Figure. A queen of the social par.pdf
 Mycocepurus ant and social parasite Figure. A queen of the social par.pdf Mycocepurus ant and social parasite Figure. A queen of the social par.pdf
Mycocepurus ant and social parasite Figure. A queen of the social par.pdf
americanopticalscbe
 
Multiple choice Select the correct answer from the list provided. 17.pdf
 Multiple choice Select the correct answer from the list provided. 17.pdf Multiple choice Select the correct answer from the list provided. 17.pdf
Multiple choice Select the correct answer from the list provided. 17.pdf
americanopticalscbe
 
Naren is dating a girl named Felicity. Naren and Felicity both cautio.pdf
 Naren is dating a girl named Felicity. Naren and Felicity both cautio.pdf Naren is dating a girl named Felicity. Naren and Felicity both cautio.pdf
Naren is dating a girl named Felicity. Naren and Felicity both cautio.pdf
americanopticalscbe
 
My code below is working fine but I just need help with the Unique.pdf
 My code below is working fine but I just need help with the Unique.pdf My code below is working fine but I just need help with the Unique.pdf
My code below is working fine but I just need help with the Unique.pdf
americanopticalscbe
 
Comprehensive Illustration (Estimated Time 60 to 75 Minutes) On Jan.pdf
Comprehensive Illustration (Estimated Time 60 to 75 Minutes) On Jan.pdfComprehensive Illustration (Estimated Time 60 to 75 Minutes) On Jan.pdf
Comprehensive Illustration (Estimated Time 60 to 75 Minutes) On Jan.pdf
americanopticalscbe
 
Consider the following (AI-generated) response to the question Why .pdf
Consider the following (AI-generated) response to the question Why .pdfConsider the following (AI-generated) response to the question Why .pdf
Consider the following (AI-generated) response to the question Why .pdf
americanopticalscbe
 

More from americanopticalscbe (20)

Nanial ano 28 ic cinclo and hac the followinn inromo and ovnoncoc in .pdf
 Nanial ano 28 ic cinclo and hac the followinn inromo and ovnoncoc in .pdf Nanial ano 28 ic cinclo and hac the followinn inromo and ovnoncoc in .pdf
Nanial ano 28 ic cinclo and hac the followinn inromo and ovnoncoc in .pdf
 
myList is an object of type ListFromOneString. myList currently con.pdf
 myList is an object of type ListFromOneString. myList currently con.pdf myList is an object of type ListFromOneString. myList currently con.pdf
myList is an object of type ListFromOneString. myList currently con.pdf
 
Name Draw the front on the following sarface imap, using rgproprixte.pdf
 Name Draw the front on the following sarface imap, using rgproprixte.pdf Name Draw the front on the following sarface imap, using rgproprixte.pdf
Name Draw the front on the following sarface imap, using rgproprixte.pdf
 
My private pilot training took place in 1977 in a Cessna 150 from Rya.pdf
 My private pilot training took place in 1977 in a Cessna 150 from Rya.pdf My private pilot training took place in 1977 in a Cessna 150 from Rya.pdf
My private pilot training took place in 1977 in a Cessna 150 from Rya.pdf
 
Multiple-Step Income Statement On March 31,20Y4, the balances of the .pdf
 Multiple-Step Income Statement On March 31,20Y4, the balances of the .pdf Multiple-Step Income Statement On March 31,20Y4, the balances of the .pdf
Multiple-Step Income Statement On March 31,20Y4, the balances of the .pdf
 
Multiple Choice decrease AD2 to AD1 Increase AS1 to AS2 Increase A.pdf
 Multiple Choice decrease AD2 to AD1 Increase AS1 to AS2 Increase A.pdf Multiple Choice decrease AD2 to AD1 Increase AS1 to AS2 Increase A.pdf
Multiple Choice decrease AD2 to AD1 Increase AS1 to AS2 Increase A.pdf
 
Mycocepurus ant and social parasite Figure. A queen of the social par.pdf
 Mycocepurus ant and social parasite Figure. A queen of the social par.pdf Mycocepurus ant and social parasite Figure. A queen of the social par.pdf
Mycocepurus ant and social parasite Figure. A queen of the social par.pdf
 
Multiple choice Select the correct answer from the list provided. 17.pdf
 Multiple choice Select the correct answer from the list provided. 17.pdf Multiple choice Select the correct answer from the list provided. 17.pdf
Multiple choice Select the correct answer from the list provided. 17.pdf
 
Nash Inc s EPS is $7.27 and its dividend payout ratio is 0.7 . If th.pdf
 Nash Inc s EPS is $7.27 and its dividend payout ratio is 0.7 . If th.pdf Nash Inc s EPS is $7.27 and its dividend payout ratio is 0.7 . If th.pdf
Nash Inc s EPS is $7.27 and its dividend payout ratio is 0.7 . If th.pdf
 
M�tiple Chaice Porffolio investment moitly represents the sole and pu.pdf
 M�tiple Chaice Porffolio investment moitly represents the sole and pu.pdf M�tiple Chaice Porffolio investment moitly represents the sole and pu.pdf
M�tiple Chaice Porffolio investment moitly represents the sole and pu.pdf
 
Naren is dating a girl named Felicity. Naren and Felicity both cautio.pdf
 Naren is dating a girl named Felicity. Naren and Felicity both cautio.pdf Naren is dating a girl named Felicity. Naren and Felicity both cautio.pdf
Naren is dating a girl named Felicity. Naren and Felicity both cautio.pdf
 
My code below is working fine but I just need help with the Unique.pdf
 My code below is working fine but I just need help with the Unique.pdf My code below is working fine but I just need help with the Unique.pdf
My code below is working fine but I just need help with the Unique.pdf
 
Muliple Chaice a pice hugw than 56 a nice .pdf
 Muliple Chaice a pice hugw than 56 a nice .pdf Muliple Chaice a pice hugw than 56 a nice .pdf
Muliple Chaice a pice hugw than 56 a nice .pdf
 
Comprehensive Illustration (Estimated Time 60 to 75 Minutes) On Jan.pdf
Comprehensive Illustration (Estimated Time 60 to 75 Minutes) On Jan.pdfComprehensive Illustration (Estimated Time 60 to 75 Minutes) On Jan.pdf
Comprehensive Illustration (Estimated Time 60 to 75 Minutes) On Jan.pdf
 
Comprehensive Problem 1 - Part 1 Taxpayer information,2022 Form 104.pdf
Comprehensive Problem 1 - Part 1 Taxpayer information,2022 Form 104.pdfComprehensive Problem 1 - Part 1 Taxpayer information,2022 Form 104.pdf
Comprehensive Problem 1 - Part 1 Taxpayer information,2022 Form 104.pdf
 
Comportamiento organizacional 2-1 Describa las dos formas princip.pdf
Comportamiento organizacional 2-1 Describa las dos formas princip.pdfComportamiento organizacional 2-1 Describa las dos formas princip.pdf
Comportamiento organizacional 2-1 Describa las dos formas princip.pdf
 
Compare DNA sequence between species to build a phylogeny. There are.pdf
Compare DNA sequence between species to build a phylogeny. There are.pdfCompare DNA sequence between species to build a phylogeny. There are.pdf
Compare DNA sequence between species to build a phylogeny. There are.pdf
 
Compare lists and tuples. Which one is not rightLists can be edi.pdf
Compare lists and tuples. Which one is not rightLists can be edi.pdfCompare lists and tuples. Which one is not rightLists can be edi.pdf
Compare lists and tuples. Which one is not rightLists can be edi.pdf
 
Consider the following data for a closed economyY =$13trillio.pdf
Consider the following data for a closed economyY =$13trillio.pdfConsider the following data for a closed economyY =$13trillio.pdf
Consider the following data for a closed economyY =$13trillio.pdf
 
Consider the following (AI-generated) response to the question Why .pdf
Consider the following (AI-generated) response to the question Why .pdfConsider the following (AI-generated) response to the question Why .pdf
Consider the following (AI-generated) response to the question Why .pdf
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 

Complete the classes shown below 1. The MinHeap Class Write necessa.pdf

  • 1. Complete the classes shown below: 1. The MinHeap Class Write necessary code in the method buildMinHeap, downHeap and upHeap. Add your necessary changes in the section where this block of code is written: /*** *** Write YOUR CODE HERE *** ***/ The driver generates a Sorted List of decreasing order using HeapSort after the specified heap operations are performed. The details of these methods are given below, also additional hints are provided in the code as comments. Also we have added helper methods for generating output. Do not edit any helper methods, they are necessary for Gradescope. Complete the code before the due date. Submit the completed MinHeap.java file via Gradescope module in folio. Details of Methods: buildMinHeap: Given an array of N elements, stored from indices 1 thru N, build a min-heap using bottom-up construction. The helper functions in the DriverPA2.java file read the size and populate the input array before calling on your buildMinHeap operation. downHeap: downHeap is an operation that is used to maintain the heap property after removing the root node from a heap. When the root node is removed, the last node in the heap is moved to the root position, and the downHeap operation is applied to this node to restore the heap property During downHeap, the node is compared with its children, and if its value is greater than the value of its children , it is swapped with the child that has the lowest value. This process is repeated until the heap property is restored. downHeap will restore the heap-order property by swapping key k along a downward path from the root. You need to maintain the Min Heap properties within the reduced size of the array. upHeap: upHeap is an operation that is used to maintain the heap property after inserting a new node into the heap. When a new node is inserted, it is placed at the bottom of the heap and the upHeap operation is applied to this node to restore the heap property. During upHeap, the node is compared with its parent, and if its value is less than the value of its parent , it is swapped with its parent. This process is repeated until the heap property is restored. upHeap will restore the heap-order property by swapping k along an upward path from the insertion node. During each insertion process, you need to ensure the MinHeap property is maintained. Input File Structure: Example: minheap0.txt 7 // Input array size(size_n) 21 16 13 12 9 7 3 // Input Array for MinHeap build (int[] minHeap) 10 30 20 5 15 // Integer array to be inserted in the MinHeap(int[] newelements) Sample Output in DriverPA2: Result after buildheap: 3 9 7 12 16 21 13 Removed Elements: 3 7 9 12 13 HeapSort result: 30 21 20 16 15 10 5 We have added 5 more input files, you can test them as well changing the file name in the Driver.java main method. These are the files: minheap1.txt minheap2.txt minheap3.txt minheap4.txt minheap5.txt Additional Notes: We have allocated the size of the Input Array more than enough capacity for convenience. The printMinHeapArray method prints the minHeap array content to the size specified. package assignment; public class MinHeap { static int[] minHeap; static int size_n; /** * Helper functions * MinHeapOperations will evaluate three operations: buildMinHeap,
  • 2. downHeap & upHeap * Parameters: * input: Integers from the Second line of input text * newelements: Integers from the Third line of input text * size: Input array size from the First line of input text * The operations to be implemented: * 1. buildMinHeap: Build the MinHeap * 2. downHeap: Algorithm downheap restores the heap-order property by swapping key k along a downward path from the root. * 3. upHeap: The upheap process is used to add a node to a heap while maintaining the Heap property. * heapSort and printMinHeapArray helper functions are added for generating the desired output. */ public String[] MinHeapOperations(int[] input, int[] newelements, int size) { // Assigning/Initiating the class static members minHeap = input.clone(); size_n = size; // These two variables are needed for Gradescope evaluation String[] results = new String[3]; String removedElements = ""; buildMinHeap(minHeap, size_n); results[0] = printMinHeapArray(minHeap, size_n); System.out.println("Result after buildheap: " + results[0]); //Remove 5 minimum numbers from the MinHeap one by one. for(int i = 0; i < 5; i++) { removedElements = removedElements + removeMin(minHeap) + " "; } results[1] = removedElements.trim(); System.out.println("Removed Elements: " + results[1]); //Insert the Elements from the newelements one by one. for (int i = 0; i < newelements.length; i++) { insert(minHeap, newelements[i]); } results[2] = heapSort(minHeap, size_n); System.out.println("HeapSort result: " + results[2]); return results; } // Helper function /* A utility function for heapSort operation */ static String heapSort(int array[], int n) { // One by one extract an element from heap for (int i = n; i > 0; i--) { // Move current root to end int temp = array[1]; array[1] = array[i]; array[i] = temp; downHeap(array, 1, i-1); } return printMinHeapArray(array, n); } // Helper function /* A utility function to print array of size n */ static String printMinHeapArray(int arr[], int n) { String result = ""; for (int i = 1; i <= n; ++i) result = result + arr[i] + " "; return result.trim(); } /** * Helper function * Remove the minimum/smallest elements from the MinHeap * During each removal process, ensure the MinHeap property. * minHeap array gets updated during this process */ public static int removeMin(int[] array) { int popped = array[1]; array[1] = array[size_n]; size_n--; downHeap(array, 1, size_n); return popped; } /* * Helper function * Insert the elements one by one in the MinHeap * Store the new item at the last empty cell in the array * minHeap array gets updated during this process */ public static void insert(int[] array, int newelement) { size_n++; int current = size_n; array[current] = newelement; upHeap(array, size_n); } /** * Build the MinHeap * minHeap array gets updated during this process */ public static void buildMinHeap(int[] array, int size) { /*** *** Write YOUR CODE HERE *** ***/ } /** * After replacing the root key with the key of the last node, the heap-order property may be violated * downHeap restores the heap-order property by swapping key k along a downward path from the node at given index */ public static void downHeap(int arr[], int index, int size) { /*** *** Write YOUR CODE HERE *** ***/ } /** * During each insertion process, ensure the MinHeap
  • 3. property. * After the insertion of a new element, the heap-order property may be violated. upHeap restores the heap-order property by swapping k along an upward path from the insertion node */ public static void upHeap(int[] array, int size) { /*** *** Write YOUR CODE HERE *** ***/ } } Driver PA2 should not be edited. package assignment; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.Scanner; public class DriverPA2 { private static int size; static int[] inputArray; // Array elements to be modified and for generating MinHeap static int[] newElementsArray; // New elements to be inserted in the Heap // Helper functions static void prepareInputDataFromText(String filename) throws FileNotFoundException, IOException{ File file = new File(filename); Scanner sc = new Scanner(file); String size_n = sc.nextLine(); size = Integer.parseInt(size_n); // Allocating the array for convenience inputArray = new int[2*size + 10]; String input = sc.nextLine(); String[] strs = input.trim().split("s+"); StringArrToIntArr(inputArray, strs, 1); input = sc.nextLine(); strs = input.trim().split("s+"); newElementsArray = new int[strs.length]; StringArrToIntArr(newElementsArray, strs, 0); sc.close(); } // Helper functions to populate array according to the need public static void StringArrToIntArr(int[] arr, String[] s, int startingindex) { //startingindex is the index from where we are populating the array from input file for (int i = 0, j = startingindex; i < s.length; i++, j++) { arr[j] = Integer.parseInt(s[i]); } } public static void main(String[] arg) throws FileNotFoundException, IOException{ // Read the file and generate output // Change the filename according to your need for testing purpose String fileName = "minheap0.txt"; prepareInputDataFromText(fileName); MinHeap minHeapObj = new MinHeap(); // This result will be evaluated in Gradescope String[] generatedResults = minHeapObj.MinHeapOperations(inputArray, newElementsArray, size); } } Test with Driver and .txt file minheap0.txt which contains 7 21 16 13 12 9 7 3 10 30 20 5 15