Question

I need the following merge-sort assignment completed using the "ArrayList<Comparable>" (the part I'm really stuck on)...

I need the following merge-sort assignment completed using the "ArrayList<Comparable>" (the part I'm really stuck on) with comments:

import java.util.ArrayList;

public class Mergesort {
    /**
     * Sorts list given using the mergesort algorithm
     * @param list the list to be sorted
     * @param first the index of the first element of the list to be sorted
     * @param last the index of the last element of the list to be sorted
     */
    public static void mergesort(ArrayList<Comparable> list, int first, int last){
    }
    /**
     * Merges two ordered sublists.
     *
     * PRE-CONDITION: list from first to mid-1 is in order, list from mid to last is in order
     * POST-CONDITION: list from first to last is in order
     *
     * @param list the list containing the ordered sublist
     * @param first first element of the first sublist
     * @param mid first element of the second sublist
     * @param last last element of the second sublist
     */
    public static void merge(ArrayList<Comparable> list, int first, int mid, int last){
    }
    public static void main(String[] args) {
    }
    //================================================
    //======= HELPER METHODS FOR TESTING BELOW =======
    //================================================
    /**
     * Returns true if two lists have the same elements.
     *
     * @param orig the original list
     * @param copy the copy of the list
     *
     * @return true if orig and copy have the same number of each element, false otherwise
     */
    private static boolean sameElements(ArrayList<Comparable> orig, ArrayList<Comparable> copy){
    }
    /**
     * Returns true if list is in ascending order
     *
     * @param list the list to check for ordering
     *
     * @return true if list is in ascending order, false otherwise
     */
    private static boolean inOrder(ArrayList<Comparable> list){
    }
    /**
     * Returns a deep copy of the given list
     *
     * @param list the list to be copied and return
     *
     * @return deep copy of argument list
     */
    private static ArrayList<Comparable> copyList(ArrayList<Comparable> list){        
    }    
    /**
     * Returns a list of Strings
     *
     * @param length the number of elements the list is to have
     *
     * @return a list of String elements with length size
     */
    private static ArrayList<Comparable> listOfStrings(int length){   
    }
    /**
     * Returns a list of Integers
     *
     * @param low the minimum number in the range of elements
     * @param high the maximum number in the range of elements
     * @param length the number of elements the list is to have
     *
     * @return a list of Integer elements with length size
     */
    private static ArrayList<Comparable> listOfInts(int low, int high, int length){   
    }
}

And here is the Pseudocode:

1. If the array has only one element, do nothing.

2. If the array has two elements, swap them if necessary.

3. Split the array into two approximately equal values.

4. Sort the first half and the second half.

5 Merge both halves together.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

MergeSort.java

import java.util.*;

public class MergeSort {
/**
* Sorts list given using the mergesort algorithm
* @param list the list to be sorted
* @param first the index of the first element of the list to be sorted
* @param last the index of the last element of the list to be sorted
*/
public static void mergesort(ArrayList<Comparable> list, int first, int last)
   {
       if( first < last )
       {
           int center = (first + last) / 2;
           mergesort(list, first, center);
           mergesort(list, center + 1, last);
           merge(list, first, center + 1, last);  
       }
}
/**
* Merges two ordered sublists.
*
* PRE-CONDITION: list from first to mid-1 is in order, list from mid to last is in order
* POST-CONDITION: list from first to last is in order
*
* @param list the list containing the ordered sublist
* @param first first element of the first sublist
* @param mid first element of the second sublist
* @param last last element of the second sublist
*/
public static void merge(ArrayList<Comparable> list, int first, int mid, int last)
   {
       int leftEnd = mid - 1;
int k = first;
int num = last - first + 1;
       ArrayList<Comparable> tmp = copyList(list);
while(first <= leftEnd && mid <= last)
if(list.get(first).compareTo(list.get(mid)) <= 0)
           {
               tmp.set(k, list.get(first));
               k++; first++;
           }
else
           {
               tmp.set(k, list.get(mid));
               k++; mid++;
           }
while(first <= leftEnd) // Copy rest of first half
       {
           tmp.set(k, list.get(first));
           k++; first++;
       }

while(mid <= last) // Copy rest of mid half
{
           tmp.set(k, list.get(mid));
           k++; mid++;
       }

// Copy tmp back
for(int i = 0; i < num; i++, last--)
list.set(last, tmp.get(last));
}
public static void main(String[] args)
   {
       MergeSort sort = new MergeSort();
       int count = 15;
       ArrayList<Comparable> ilist = MergeSort.listOfInts(10, 100, count);
       ArrayList<Comparable> slist = MergeSort.listOfStrings(count);
       for(int i=0; i<count; i++) System.out.print(ilist.get(i)+" ");
       System.out.println();
       for(int i=0; i<count; i++) System.out.print(slist.get(i)+" ");
       System.out.println();
       sort.mergesort(ilist, 0, count-1);
       sort.mergesort(slist, 0, count-1);
       for(int i=0; i<count; i++) System.out.print(ilist.get(i)+" ");
       System.out.println();
       System.out.println("integer array is sorted: "+ MergeSort.inOrder(ilist));
       for(int i=0; i<count; i++) System.out.print(slist.get(i)+" ");
       System.out.println();
       System.out.println("string array is sorted: "+ MergeSort.inOrder(slist));
}
//================================================
//======= HELPER METHODS FOR TESTING BELOW =======
//================================================
/**
* Returns true if two lists have the same elements.
*
* @param orig the original list
* @param copy the copy of the list
*
* @return true if orig and copy have the same number of each element, false otherwise
*/
private static boolean sameElements(ArrayList<Comparable> orig, ArrayList<Comparable> copy)
   {
       for(int i=1; i<orig.size(); i++)
       {
           if(orig.get(i).compareTo(copy.get(i))==0) return false;
       }
       return true;
}
/**
* Returns true if list is in ascending order
*
* @param list the list to check for ordering
*
* @return true if list is in ascending order, false otherwise
*/
private static boolean inOrder(ArrayList<Comparable> list)
   {
       for(int i=1; i<list.size(); i++)
       {
           if(list.get(i).compareTo(list.get(i-1))<0) return false;
       }
       return true;
}
/**
* Returns a deep copy of the given list
*
* @param list the list to be copied and return
*
* @return deep copy of argument list
*/
private static ArrayList<Comparable> copyList(ArrayList<Comparable> list)
   {
       ArrayList<Comparable> tmp = new ArrayList<Comparable>(list.size());
       for(int i=0; i<list.size(); i++)
           tmp.add(list.get(i));
       return tmp;  
}
/**
* Returns a list of Strings
*
* @param length the number of elements the list is to have
*
* @return a list of String elements with length size
*/
private static ArrayList<Comparable> listOfStrings(int length)
   {
       String AlphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz";
       ArrayList<Comparable> list = new ArrayList<Comparable>(length);                          
       for(int j=0; j<length; j++)
       {
           StringBuilder sb = new StringBuilder(10);
           for (int i = 0; i < 10; i++)
           {
               // generate a random number between
               // 0 to AlphaNumericString variable length
               int index
                   = (int)(AlphaNumericString.length()
                           * Math.random());
               // add Character one by one in end of sb
               sb.append(AlphaNumericString
                           .charAt(index));
           }
           list.add(sb.toString());
       }
       return list;  
}
/**
* Returns a list of Integers
*
* @param low the minimum number in the range of elements
* @param high the maximum number in the range of elements
* @param length the number of elements the list is to have
*
* @return a list of Integer elements with length size
*/
private static ArrayList<Comparable> listOfInts(int low, int high, int length)
   {
       ArrayList<Comparable> list = new ArrayList<Comparable>(length);
       Random randomGenerator = new Random();
       for(int i=0; i<length; i++)
       list.add(low + randomGenerator.nextInt(high-low) + 1);
       return list;
}
}

Add a comment
Know the answer?
Add Answer to:
I need the following merge-sort assignment completed using the "ArrayList<Comparable>" (the part I'm really stuck on)...
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
  • Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. E...

    Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. Execute the sort algorithms against the same list, recording information for the total number of comparisons and total execution time for each algorithm. Try several different lists, including at least one that is already in sorted order. ---------------------------------------------------------------------------------------------------------------- /** * Sorting demonstrates sorting and searching on an...

  • I am currently using eclipse to write in java. A snapshot of the output would be...

    I am currently using eclipse to write in java. A snapshot of the output would be greatly appreciated to verify that the program is indeed working. Thanks in advance for both your time and effort. Here is the previous exercise code: /////////////////////////////////////////////////////Main /******************************************* * Week 5 lab - exercise 1 and exercise 2: * * ArrayList class with search algorithms * ********************************************/ import java.util.*; /** * Class to test sequential search, sorted search, and binary search algorithms * implemented in...

  • In this assignment you will implement merge-sort algorithm by creating 2 threads instead of 2 pro...

    In this assignment you will implement merge-sort algorithm by creating 2 threads instead of 2 processes. First half of the array will be sorted by thread 1 and the second half by thread 2. When the threads complete their tasks, the main program will merge the half arrays. You should not waste your time on merge-sort algorithm. Use the merge sort algorithm given below void mergesort(int a[],int i,int j) { int mid; if(i<j) { mid=(i+j)/2; mergesort(a,i,mid); //left recursion mergesort(a,mid+1,j); //right...

  • Please merge all the codes below and add comments using JAVA Program. I need a complete...

    Please merge all the codes below and add comments using JAVA Program. I need a complete code which is the combination of the following codes: // Merges the left/right elements into a sorted result. // Precondition: left/right are sorted public static void merge(int[] result, int[] left,                                        int[] right) {     int i1 = 0;   // index into left array     int i2 = 0;   // index into right array     for (int i = 0; i < result.length; i++)...

  • HW58.1. Array Merge Sort You've done merge (on Lists), so now it's time to do merge...

    HW58.1. Array Merge Sort You've done merge (on Lists), so now it's time to do merge sort (on arrays). Create a public non-final class named Mergesort that extends Merge. Implement a public static method int[] mergesort(int[] values) that returns the input array of ints sorted in ascending order. You will want this method to be recursive, with the base case being an array with zero or one value. If the passed array is null you should return null. If the...

  • USE JAVA PROGRAMMING Create a program that would collect list of persons using double link list...

    USE JAVA PROGRAMMING Create a program that would collect list of persons using double link list and use a Merge Sort to sort the object by age. Create a class called Person : name and age Create methods that add, and delete Person from the link list Create a method that sorts the persons' objects by age. package mergesort; public class MergeSortExample { private static Comparable[] aux; // auxiliary array for merges public static void sort(Comparable[] a) { aux =...

  • Using Merge Sort: (In Java) (Please screenshot or copy your output file in the answer) In...

    Using Merge Sort: (In Java) (Please screenshot or copy your output file in the answer) In this project, we combine the concepts of Recursion and Merge Sorting. Please note that the focus of this project is on Merging and don't forget the following constraint: Programming Steps: 1) Create a class called Art that implements Comparable interface. 2) Read part of the file and use Merge Sort to sort the array of Art and then write them to a file. 3)...

  • Write a method public static ArrayList merge(ArrayList a, ArrayList b) that merges two array lists, alternating...

    Write a method public static ArrayList merge(ArrayList a, ArrayList b) that merges two array lists, alternating elements from both array lists. If one array list is shorter than the other, then alternate as long as you can and then append the remaining elements from the longer array list. For example, if a is 1 4 9 16 and b is 9 7 4 9 11 then merge returns the array list 1 9 4 7 9 4 16 9 11...

  • Java Programming Write a program to find the number of comparison using binarySearch and the sequentialSearch...

    Java Programming Write a program to find the number of comparison using binarySearch and the sequentialSearch algorithms as follows: Suppose list is an array of 2500 elements. 1. Use a random number generator to fill list; 2. Use a sorting algorithm to sort list; 3. Search list for some items as follows: a) Use the binary search algorithm to search list (please work on SearchSortAlgorithms.java and modify the algorithm to count the number of comparisons) b) Use the sequential search...

  • Please help me to solve the problem with java language! An implementation of the Merge Sort...

    Please help me to solve the problem with java language! An implementation of the Merge Sort algorithm. Modify the algorithm so that it splits the list into 3 sublists (instead of two). Each sublist should contain about n/3 items. The algorithm should sort each sublist recursively and merge the three sorted sublists. The traditional merge sort algorithm has an average and worst-case performance of O(n log2 n). What is the performance of the 3-way Merge Sort algorithm? Merge Sort algorithm...

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