Question

In: Computer Science

Modify the MergeSort program given to support searching subarrays. Program is listed below in Java. public...

Modify the MergeSort program given to support searching subarrays.

Program is listed below in Java.

public class Merge

{

public static void sort(Comparable[] a)

}

Comparable[] aux = new Comparable[a.length];

sort(a, aux, 0, a.length);

}

private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi)

{ //Sort a[lo, hi)

if (hi - lo <= 1) return;

int mid = lo (hi + lo) / 2;

sort( a, aux, lo, mid);

sort(a, aux, mid, hi);

int i = lo, j = mid;

for (int k = lo; k < hi; k++)

if (i == mid) aux[k] = a[j++];

else if (j == hi) aux[k] = a[i++];

else if (a[j].compareTo(a[i]) < 0) aux[k] = a[j++];

else aux[k] = a[i++];

for (int k = lo; k < hi; k++)

a[k] = aux[k];

}

public static void main(String[] args)

{ }

}

Note: The user would give an unsorted list of words as command-line arguments along with the starting and ending index of the subarray that should be sorted. The program should print out a list where the strings between the given indexes are sorted alphabetically.

  • Sample runs would be as follows.

>java MergeSort 2 4 toy apply sand bay cat dog fish

toy apply bay cat sand dog fish

>java MergeSort 0 3 was had him and you his the but

and had him was you his the but

Solutions

Expert Solution


//Having Any query Please ask in comment Section

class Merge {

  
   //Merging
   void merge(String arr[], int l, int m, int r) {

       int n1 = m - l + 1;
       int n2 = r - m;

       String L[] = new String[n1];
       String R[] = new String[n2];

       for (int i = 0; i < n1; ++i)
           L[i] = arr[l + i];
       for (int j = 0; j < n2; ++j)
           R[j] = arr[m + 1 + j];


       int i = 0, j = 0;

       int k = l;
       while (i < n1 && j < n2) {
           if (stringCompare(L[i], R[j]) < 0) {
               arr[k] = L[i];
               i++;
           } else {
               arr[k] = R[j];
               j++;
           }
           k++;
       }

       while (i < n1) {
           arr[k] = L[i];
           i++;
           k++;
       }

       while (j < n2) {
           arr[k] = R[j];
           j++;
           k++;
       }
   }

  
   //Sorting
   void sort(String arr[], int l, int r) {
       if (l < r) {
           // Find the middle point
           int m = (l + r) / 2;

           // Sort first and second halves
           sort(arr, l, m);
           sort(arr, m + 1, r);

           // Merge the sorted halves
           merge(arr, l, m, r);
       }
   }

  
   //Comparison
   public static int stringCompare(String str1, String str2) {

       int l1 = str1.length();
       int l2 = str2.length();
       int lmin = Math.min(l1, l2);

       for (int i = 0; i < lmin; i++) {
           int str1_ch = (int) str1.charAt(i);
           int str2_ch = (int) str2.charAt(i);

           if (str1_ch != str2_ch) {
               return str1_ch - str2_ch;
           }
       }
      
       if (l1 != l2) {
           return l1 - l2;
       }

       else {
           return 0;
       }
   }

   public static void main(String[] args) {
       int start = Integer.parseInt(args[0]);            //Separating start point
       int end = Integer.parseInt(args[1]);        //Separating End point

       String[] a = new String[args.length-2];           //Separating String Values
      
      
       //Subarray For required Sort String
       String subarray[] = new String[(end - start)+1];
       int j=0;
       for(int i=0;i<a.length;i++) {
           a[i] = args[i+2];
           if(i>=start && i<=end) {
               subarray[j] = a[i];
               j++;
           }
       }
      
      
      
      
       //Sorting
       Merge merge = new Merge();
       merge.sort(subarray, 0, subarray.length-1);
      
      
       //Combining Sort array with Remaining Values
      
       String finalString = "";
       int sub=0;
       for (int i = 0; i < a.length; i++) {
           if(i>=start && i<=end) {
               finalString+=" "+subarray[sub];
               sub++;
           }else {
               finalString+=" "+a[i];
              
           }
       }
       System.out.println(finalString.trim());
      
   }
}

 

 

Related Solutions

write program that develop a Java class Dictionary to support the following public methods of an...
write program that develop a Java class Dictionary to support the following public methods of an abstract data type: public class Dictionary { // insert a (key, value) pair into the Dictionary, key value must be unique, the value is associated with the key; only the last value inserted for a key will be kept public void insert(String key, String value); // return the value associated with the key value public String lookup(String key); // delete the (key, value) pair...
Java programming: Save the program as DeadlockExample.java   Run the program below.  Note whether deadlock occurs.  Then modify the...
Java programming: Save the program as DeadlockExample.java   Run the program below.  Note whether deadlock occurs.  Then modify the program to add two more threads: add a class C and a class D, and call them from main.  Does deadlock occur? import java.util.concurrent.locks.*; class A implements Runnable {             private Lock first, second;             public A(Lock first, Lock second) {                         this.first = first;                         this.second = second;             }             public void run() {                         try {                                     first.lock();                                     System.out.println("Thread A got first lock.");                                     // do something                                     try {                                                 Thread.sleep( ((int)(3*Math.random()))*1000);...
PROGRAM SIMULATION. Understand the given JAVA program and write the output. 1.     public class Places        {...
PROGRAM SIMULATION. Understand the given JAVA program and write the output. 1.     public class Places        {            public static void main(String args[])            {                   String place[]=new String[4];           place[0]="Salmaniya"; place[1]="Salmabad"; place[2]="Isa Town"; place[3] = “Manama”         System.out.println(place[3]);         System.out.println(place[1].toLowerCase());         System.out.println(place[2].substring(4,6);         System.out.println(place[3].charAt(4));         System.out.println(place[1].equals(place[2]));            } }    b. public class ChangeIt { public void doIt( int[] z ) { z[0] = 0; } } public class TestIt { public static void main ( String[] args ) {...
Guidelines for the program: All methods listed below must be public and static. If your code...
Guidelines for the program: All methods listed below must be public and static. If your code is using a loop to modify or create a string, you need to use the StringBuilder class from the API. Keep the loops simple but also efficient. Remember that you want each loop to do only one "task" while also avoiding unnecessary traversals of the data. No additional methods are needed. However, you may write additional private helper methods, but you still need to...
HELLO CAN YOU PLEASE DO THIS JAVA PROGRAM WITH THE DIFFERNT CLASSES LISTED BELOW. I WILL...
HELLO CAN YOU PLEASE DO THIS JAVA PROGRAM WITH THE DIFFERNT CLASSES LISTED BELOW. I WILL LEAVE AWESOME RATING. THANK YOU IN ADVANCE. The code needed for this assignment has to somehow implement a stack interface (including a vector stack, array stack, and a linked stack). The classes needed are the Game class, the disk class, the driver, and the stack interface (including arraystack, linkedstack, and vectorstack) QUESTION Suppose you are designing a game called King of the Stacks. The...
Write a JAVA program to modify the insert and remove of a binary search tree to...
Write a JAVA program to modify the insert and remove of a binary search tree to become an AVL tree.
Write the following Java code into Pseudocode import java.util.*; public class Main { // Searching module...
Write the following Java code into Pseudocode import java.util.*; public class Main { // Searching module public static void score_search(int s,int score[]) { // Initialise flag as 0 int flag=0; // Looping till the end of the array for(int j=0;j<10;j++) { // If the element is found in the array if(s==score[j]) { // Update flag to 1 flag=1; } } // In case flag is 1 element is found if(flag==1) { System.out.println("golf score found"); } // // In case flag...
Question: Java Programming. ** Modify Current Program. Current Program class Account{       //instance variables   ...
Question: Java Programming. ** Modify Current Program. Current Program class Account{       //instance variables    private long accountNumber;    private String firstName;    private String lastName;    private double balance;       //constructor    public Account(long accountNumber, String firstName, String lastName, double balance) {        this.accountNumber = accountNumber;        this.firstName = firstName;        this.lastName = lastName;        this.balance = balance;    }    //all getters and setters    public long getAccountNumber() {        return...
Modify Java program to accept a telephone number with any numberof the letters, using the...
Modify Java program to accept a telephone number with any number of the letters, using the if else loop. The output should display a hyphen after the first 3 digits and subsequently a hyphen (-) after every four digits. Also, modify the program to process as many telephone numbers as the user wants.
in java code Modify your program as follows: Ask the user for the number of hours...
in java code Modify your program as follows: Ask the user for the number of hours worked in a week and the number of dependents as input, and then print out the same information as in the initial payroll assignment. Perform input validation to make sure the numbers entered by the user are reasonable (non-negative, not unusually large, etc). Let the calculations repeat for several employees until the user wishes to quit the program. Remember: Use variables or named constants...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT