Question

In Java 1. Write merge method for mergeSort method. 2. Write MaxheapPriorityQueue constructor, which takes an...

In Java
1. Write merge method for mergeSort method.
2. Write MaxheapPriorityQueue constructor, which takes an array of data, and construct the max
heap priority queue using bottom-up algorithm. Assuming bubbleDown method is provided.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer :

Step 1 : MergeSort method. in java

Mergesort is a divide and conquer algorithm., Divide and conquer algorithms divide the original data into smaller sets of data to solve the problem. Steps to implement Merge Sort:

  • Divide the unsorted array into n partitions, each partition contains 1 element. Here the one element is considered as sorted.
  • Repeatedly merge partitioned units to produce new sublists until there is only 1 sublist remaining. This will be the sorted list at the end
  • Merge sort is a fast, stable sorting routine with guaranteed O(n*log(n)) efficiency.

Algorithm

  • Step 1: [INITIALIZE] SET I = BEG, J = MID + 1, INDEX = 0
  • Step 2: Repeat while (I <= MID) AND (J<=END)
    IF ARR[I] < ARR[J]
    SET TEMP[INDEX] = ARR[I]
    SET I = I + 1
    ELSE
    SET TEMP[INDEX] = ARR[J]
    SET J = J + 1
    [END OF IF]
    SET INDEX = INDEX + 1
    [END OF LOOP]
    Step 3: [Copy the remaining
    elements of right sub-array, if
    any]
    IF I > MID
    Repeat while J <= END
    SET TEMP[INDEX] = ARR[J]
    SET INDEX = INDEX + 1, SET J = J + 1
    [END OF LOOP]
    [Copy the remaining elements of
    left sub-array, if any]
    ELSE
    Repeat while I <= MID
    SET TEMP[INDEX] = ARR[I]
    SET INDEX = INDEX + 1, SET I = I + 1
    [END OF LOOP]
    [END OF IF]
  • Step 4: [Copy the contents of TEMP back to ARR] SET K = 0
  • Step 5: Repeat while K < INDEX
    SET ARR[K] = TEMP[K]
    SET K = K + 1
    [END OF LOOP]
  • Step 6: Exit

Java Program :

import java.util.*;

public class MergerSort

{

    public static void main(String[] args)

    {

        //Unsorted array

        Integer[] a = { 2, 6, 3, 5, 1 };

         

        //Call merge sort

        mergeSort(a);

System.out.println(Arrays.toString(a));

    }

    @SuppressWarnings("rawtypes")

    public static Comparable[] mergeSort(Comparable[] list)

    {

        //If list is empty; no need to do anything

        if (list.length <= 1) {

            return list;

        }

         

        //Split the array in half in two parts

        Comparable[] first = new Comparable[list.length / 2];

        Comparable[] second = new Comparable[list.length - first.length];

        System.arraycopy(list, 0, first, 0, first.length);

        System.arraycopy(list, first.length, second, 0, second.length);

         

        //Sort each half recursively

        mergeSort(first);

        mergeSort(second);

         

        //Merge both halves together, overwriting to original array

        merge(first, second, list);

        return list;

    }

     

    @SuppressWarnings({ "rawtypes", "unchecked" })

    private static void merge(Comparable[] first, Comparable[] second, Comparable[] result)

    {

        //Index Position in first array - starting with first element

        int iFirst = 0;

         

        //Index Position in second array - starting with first element

        int iSecond = 0;

         

        //Index Position in merged array - starting with first position

        int iMerged = 0;

         

        //Compare elements at iFirst and iSecond,

        //and move smaller element at iMerged

        while (iFirst < first.length && iSecond < second.length)

        {

            if (first[iFirst].compareTo(second[iSecond]) < 0)

            {

                result[iMerged] = first[iFirst];

                iFirst++;

            }

            else

            {

                result[iMerged] = second[iSecond];

                iSecond++;

            }

            iMerged++;

        }

        //copy remaining elements from both halves - each half will have already sorted elements

        System.arraycopy(first, iFirst, result, iMerged, first.length - iFirst);

        System.arraycopy(second, iSecond, result, iMerged, second.length - iSecond);

    }

}

Step 2 :Write MaxheapPriorityQueue constructor, which takes an array of data, and construct the max

heap priority queue using bottom-up algorithm. Assuming bubbleDown method is provided

Answer : In this type of heap, the value of parent node will always be greater than or equal to the value of child node across the tree and the node with highest value will be the root node of the tree.

void max_heapify (int Arr[ ], int i, int N)
{
    int left = 2*i                   //left child
    int right = 2*i +1           //right child
    if(left<= N and Arr[left] > Arr[i] )
          largest = left;
    else
         largest = i;
    if(right <= N and Arr[right] > Arr[largest] )
        largest = right;
    if(largest != i )
    {
        swap (Ar[i] , Arr[largest]);
        max_heapify (Arr, largest,N);
    } 
 }
Add a comment
Know the answer?
Add Answer to:
In Java 1. Write merge method for mergeSort method. 2. Write MaxheapPriorityQueue constructor, which takes an...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write MaxheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority queue...

    Write MaxheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority queue using bottom-up algorithm. Assuming bubbleDown method is provided. What is the best-case and worst-case of insertionSort? What is the best-case and worst-case of mergeSort? What is the best-case and worst-case of quickSort?

  • 2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority...

    2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority queue using bottom-up algorithm. The expected run time should be O(n), where n is the total number of data. BubbleDown method is provided. You may test it in this minHeap public class MinHeapPriorityQueue<E extends Comparable<? super E>>{ private E data[]; private int size; public MinHeapPriorityQueue(){ this(100); } public MinHeapPriorityQueue(int cap){ size = 0; data = (E[]) new Comparable[cap]; } public MinHeapPriorityQueue(int[] a){ } public...

  • Write merge method for mergeSort method, it takes the array of data, starting index of first...

    Write merge method for mergeSort method, it takes the array of data, starting index of first half, starting index of second half and end index of second half. please use the code below to test it public class A4Sort{ public static void mergeSort(int[] a, int l, int h){ if (l >= h) return; int mid = (h + l) / 2; mergeSort(a, l, mid); mergeSort(a, mid + 1, h); merge(a, l, mid + 1, h); } public static void main(String[]...

  • 1.) Complete the merge method below, which is the merge step of MergeSort. That is, it...

    1.) Complete the merge method below, which is the merge step of MergeSort. That is, it takes two sorted arrays as input and returns a new sorted array that contains all the elements from the two input arrays. Furthermore, it should keep all duplicated values, and it should run in O(n) time, where n is the size of the output array. public static int[] main(int[] a, int[] b) { }

  • Write a program in Java to implement the max-priority queue using max-heap data structure. Implement the...

    Write a program in Java to implement the max-priority queue using max-heap data structure. Implement the max-heap data structure using an integer array of 10 cells. (Do not use Java in-built PriorityQueue class.) [In a max-heap, the root node and the intermediate node vales are always greater than their children.] First, take 10 integer values from the user and insert them in the max-priority queue. Then print the elements of the queue. After that, delete two elements from the queue...

  • Write A JAVA mergesort method that mergesorts array elements in descending order. Write A JAVA binary...

    Write A JAVA mergesort method that mergesorts array elements in descending order. Write A JAVA binary search method that searches x in a sorted array with n elements and returns its position if exist, -1 otherwise.

  • In class, we discussed the priority queue (PQ) ADT implemented using min-heap. In a min-heap, the...

    In class, we discussed the priority queue (PQ) ADT implemented using min-heap. In a min-heap, the element of the heap with the smallest key is the root of the binary tree. On the other hand, a max-heap has as root the element with the biggest key, and the relationship between the keys of a node and its parent is reversed of that of a min-heap. We also discussed an array-based implementation of heaps. In this assignment, your task is to...

  • Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an...

    Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an array of elements as a parameter and uses that array as the heap rather than creating a new array. Of course, the array passed in is probably not in proper heap ordering, so you must rearrange it until it is. There's a neat trick for achieving this: If you just "bubble down" all of the non-leaf nodes of the heap, starting from the last...

  • Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an...

    Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an array of elements as a parameter and uses that array as the heap rather than creating a new array. Of course, the array passed in is probably not in proper heap ordering, so you must rearrange it until it is. There's a neat trick for achieving this: If you just "bubble down" all of the non-leaf nodes of the heap, starting from the last...

  • 2. Short programming assignment. Implement a bottom-up mergesort that first sorts blocks of M elements using...

    2. Short programming assignment. Implement a bottom-up mergesort that first sorts blocks of M elements using insertion sort. Test your program with large sets of random data and determine what value of M works best. 3. The following refer to linked list mergesort Explain why mergesort is more suitable for linked lists than other sorting methods. a. Explain why mergesort is more suitable for linked lists than other b. Consider a file that is “mostly sorted.” Explain how the principles...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT