Question

Create a program called Merge.java that implements a variety of the Merge function (in the Merge...

Create a program called Merge.java that implements a variety of the Merge function (in the Merge Sort algorithm). The program should be able to do the following: accepts two command line parameters, each specifies a text file containing the integers to be merged. The structure of the files is as follows: For both files, there will be multiple lines, each of which contains one integer. The number of lines is unknown. reads the integers from the text files into two corresponding array of integers. sorts the array from first file using InsertionSort in ascending order. sorts the array from the second file using InsertionSort in descending order. merges the two arrays into one large array sorted in descending order. There must be no resorting of this array after the merging process is completed. prints out the sorted version (ascending order)of the first array on a single line, with the integers separated by a single white space. prints out a sorted version (descending order) of the second array on a single line, with the integers separated by a single white space. prints out a sorted version (descending order) of the merged array on a single line, with the integers separated by a single white space.

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

// Merge.java Java program to read the numbers of two files in 2 arrays and sort first file in ascending order
// and second file in descending order and then merge both the arrays in another array in descending order
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Merge {
  
   // method to sort the array using insertion sort in ascending or descending order based on the value of ascending
   public static void insertionSort(int array[], boolean ascending)
   {
       int i,j;
       int key;
       // sorting in ascending order
       if(ascending)
       {
           for(i=1;i<array.length;i++)
           {
               j = i-1;
               key = array[i];
              
               while(j>=0 && array[j] > key)
               {
                   array[j+1] = array[j];
                   j--;
               }
              
               array[j+1] = key;
           }
       }else // sorting in descending order
       {
           for(i=1;i<array.length;i++)
           {
               j = i-1;
               key = array[i];
              
               while(j>=0 && array[j] < key)
               {
                   array[j+1] = array[j];
                   j--;
               }
              
               array[j+1] = key;
           }  
       }
   }
  
   // method to merge the arrays array1 and array2 in descending order
   // array1 is sorted in ascending order and array2 is sorted in descending order
   public static int[] merge(int array1[], int array2[])
   {
       // create the resultant array of size of total number of elements in array1 and array2
       int result[] = new int[array1.length+array2.length];
       int i,j,k;
       // loop to merge the numbers from array1 and array2 in descending order
       // array1 starts at the end and goes to first
       // array2 starts at the first and goes to end
       for(i=array1.length-1,j=0,k=0 ; i>=0 && j<array2.length;k++ )
       {
           // if element in array1 > element in array2, insert array1 element
           if(array1[i] >= array2[j])
           {
               result[k] = array1[i];
               i--;
           }else // if element in array2 > element in array1, insert array2 element
           {
               result[k] = array2[j];
               j++;
           }
       }
      
       // if any element from array1 is left, insert it
       for(;i>=0 ;i--,k++)
       {
           result[k] = array1[i];
       }
      
       // if any element from array2 is left insert it
       for(;j<array2.length;j++,k++)
           result[k] = array2[j];
      
       return result; // return the resultant sorted array
   }

   public static void main(String[] args) throws FileNotFoundException {

       // check number of arguments is not < 2, if it is then display error and exit
       if(args.length < 2)
       {
           System.out.println("Expected 2 input filenames as command line arguments");
       }else
       {
           // create file objects for both the files
           File file1 = new File(args[0]);
           File file2 = new File(args[1]);
          
           // check if both files exist
           if(file1.exists() && file2.exists())
           {
               // create scanner object to read both the files
               Scanner fileScan1 = new Scanner(file1);
               Scanner fileScan2 = new Scanner(file2);
              
// create 2 arrays of initially 0 size      
               int array1[] = new int[0];
               int array2[] = new int[0];
               int num;
               // loop to read first file in array1
               while(fileScan1.hasNextInt())
               {
                   num = fileScan1.nextInt();
                   array1 = Arrays.copyOf(array1, array1.length+1);
                   array1[array1.length-1] = num;
               }
              
               fileScan1.close(); // close the first file
               // loop to read second file in array2
               while(fileScan2.hasNextInt())
               {
                   num = fileScan2.nextInt();
                   array2 = Arrays.copyOf(array2, array2.length+1);
                   array2[array2.length-1] = num;
               }
              
               fileScan2.close(); // close the second file
               // sort the array1 in ascending order
               insertionSort(array1,true);
               // sort the array1 in descending order
               insertionSort(array2,false);
               // merge both the arrays in descending order
               int result[] = merge(array1,array2);
              
               // display the arrays
               System.out.println("Array 1 :");
               for(int i=0;i<array1.length;i++)
                   System.out.print(array1[i]+" ");
               System.out.println("\nArray 2 : ");
               for(int i=0;i<array2.length;i++)
                   System.out.print(array2[i]+" ");
              
               System.out.println("\nMerged Array : ");
               for(int i=0;i<result.length;i++)
                   System.out.print(result[i]+" ");
              
           }else // if file(s) doesn't exist, display error
               System.out.println("File(s) doesn't exist");
       }

   }

}
//end of Merge.java

Output:

Input file1 : numbers1.txt

Input file 2 : numbers2.txt

Output:

java Merge numbers1.txt numbers2.txt

Add a comment
Know the answer?
Add Answer to:
Create a program called Merge.java that implements a variety of the Merge function (in the Merge...
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 a program to merge two sorted arrays into a third array. Ask the user to...

    Write a program to merge two sorted arrays into a third array. Ask the user to enter the size of the two arrays. The length of array1 could be greater than, equal to or less than the length of array2. Fill both with random numbers 0-99. Sort both arrays as explained below. Write a method merge that takes the two arrays as arguments. The method returns a merged array with size equal to the size of both arrays combined. Note:...

  • Create a java project. Create a class called cls2DarrayProcessor.java. with the following: Reads numbers from a...

    Create a java project. Create a class called cls2DarrayProcessor.java. with the following: Reads numbers from a pre-defined text file. A: Text file name should be data.txt B: Text file should be in the same workspace directory of your project's folder C: Text file name should be STORED in a String and called: String strFile ='./data.txt' Defines a 2-D array of integers with dimensions of 5 rows by 5 columns. Inserts the data from the text file to the 2-D array...

  • Write a multithreaded sorting program that works as follows: A list of integers is divided into...

    Write a multithreaded sorting program that works as follows: A list of integers is divided into two smaller lists of equal size. Two separate threads (which we will term sorting threads) sort each sublist using a sorting algorithm of your choice. The two sublists are then merged by a third thread—a merging thread —which merges the two sublists into a single sorted list. Because global data are shared cross all threads, perhaps the easiest way to set up the data...

  • This program should test the running time of these algorithms: Selection Sort Insertion Sort Bubble Sort...

    This program should test the running time of these algorithms: Selection Sort Insertion Sort Bubble Sort Merge Sort Quick Sort Heap Sort You have access to the implementation of all of these sorting algorithms, and you may use what is provided in your text directly. Be sure to cite the source of these implementations in the header of your program. Please maintain the property that these sorting algorithms sort arrays in ascending order. For this homework, you will write a...

  • c++ 10. Code the template function merge, which merges two ranges into a single output container. The first two argu- ments indicate one range and the next two indicate the other range. The last argu...

    c++ 10. Code the template function merge, which merges two ranges into a single output container. The first two argu- ments indicate one range and the next two indicate the other range. The last argument is a container witha push back function. The input ranges are sorted into ascending order and operatorc is available to compare el- ements of these ranges. The output container should also be sorted into the same order. If an element from one container is equal...

  • Homework 1- Merge Files: 1. Design a class named MergeFiles 1 Three file names are passed...

    Homework 1- Merge Files: 1. Design a class named MergeFiles 1 Three file names are passed as command-line arguments to MergeFiles as follows: java MergeFiles filel file2 mergedFile II. MergeFiles reads names stored in files file and file2 III. Merges the two list of names into a single list IV. Sorts that single list V. Ignores repetitions VI. Writes the sorted, free-of-repetitions list to a new file named mergedFile.txt VII. The names in all three files are stored as one...

  • The file Sorting.java contains the Sorting class from Listing 9.9 in the text. This class implements...

    The file Sorting.java contains the Sorting class from Listing 9.9 in the text. This class implements both the selection sort and the insertion sort algorithms for sorting any array of Comparable objects in ascending order. In this exercise, you will use the Sorting class to sort several different types of objects. 1. The file Numbers.java reads in an array of integers, invokes the selection sort algorithm to sort them, and then prints the sorted array. Save Sorting.java and Numbers.java to...

  • Instructions C++ programming Your task is to write a class called Data, stored in a file...

    Instructions C++ programming Your task is to write a class called Data, stored in a file named Data.h. Your class should be able to store a collection (vector) of integers. In addition to the appropriate constructors, your class should also have the following methods. void add (int number); Adds a number to the data set. void print (); Prints out the entire data set on a single line, separated by space. void sort (); Sorts the data set in ascending...

  • Programming language --> Matlab The name of a text file Outputs: (cell) An Nx2 cell array...

    Programming language --> Matlab The name of a text file Outputs: (cell) An Nx2 cell array listing words and their counts in sorted order Function Description: Have you ever seen those fancy word-clouds based on the frequency of word occurrences in some text? Well the first step of making a graphic like that is to figure out how often the words in some text occur, which is exactly what this function will do. You will count the number of occurrences...

  • Write a menu based program implementing the following functions: (0) Write a function called displayMenu that...

    Write a menu based program implementing the following functions: (0) Write a function called displayMenu that does not take any parameters, but returns an integer representing your user's menu choice. Your program's main function should only comprise of the following: a do/while loop with the displayMenu function call inside the loop body switch/case, or if/else if/ ... for handling the calls of the functions based on the menu choice selected in displayMenu. the do/while loop should always continue as long...

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
ADVERTISEMENT