Question

In: Computer Science

2. Write a Java program that reads a series of input lines from given file “name.txt”,...

2. Write a Java program that reads a series of input lines from given file “name.txt”, and sorts them into alphabetical order, ignoring the case of words. The program should use the merge sort algorithm so that it efficiently sorts a large file.

Contents of names.text

Slater, KendallLavery, RyanChandler, Arabella "Babe"Chandler, StuartKane, EricaChandler, Adam JrSlater, ZachMontgomery, JacksonChandler, KrystalMartin, JamesMontgomery, BiancaCortlandt, PalmerDevane, AidanMadden, JoshHayward, DavidLavery,k JonathanSmythe, GreenleeCortlandt, OpalMcDermott, AnnieHenry, DiGrey, MariaEnglish, BrookeKeefer, JuliaMartin, JosephMontgomery, LilyDillon, AmandaColby, LizaStone, Mary FrancesChandler, ColbyFrye, DerekMontgomery, ReggieMontgomery, SeanSantos, HayleySantos, MateoDillon, JanetJefferson, KelseyChandler, MarianFargate, MyrtleHenry, DelCodahy, LiviaWarner, AnitaLavery, SpikeMartin, RuthMontgomery, Barbara

Solutions

Expert Solution

ANSWER:

I have provided the properly commented and indented code so you can easily copy the code as well as check for correct indentation.
I have provided the output image of the code so you can easily cross-check for the correct output of the code.
Have a nice and healthy day!!

CODE

import java.util.*;
import java.io.*;

public class Main
{

  public static String [] mergeSort(String [] array){
        String [] list = array;
        
        if(list.length > 1)
        {
            // mid of list
            int mid = list.length / 2;
 
            // Split left part
            String[] left = new String[mid];
            for(int i = 0; i < mid; i++)
            {
                left[i] = list[i];
            }
             
            // Split right part
            String[] right = new String[list.length - mid];
            for(int i = mid; i < list.length; i++)
            {
                right[i - mid] = list[i];
            }
            // calling mergeSort
            mergeSort(left);
            mergeSort(right);
 
            int i = 0;
            int j = 0;
            int k = 0;
 
            // Merge left and right arrays
            while(i < left.length && j < right.length)
            {
                // compare left right string
                // using
                if(left[i].compareTo(right[j]) < 0)
                {
                    list[k] = left[i];
                    i++;
                }
                else
                {
                    list[k] = right[j];
                    j++;
                }
                k++;
            }
            // Collect remaining elements
            while(i < left.length)
            {
                list[k] = left[i];
                i++;
                k++;
            }
            while(j < right.length)
            {
                list[k] = right[j];
                j++;
                k++;
            }
        }
        

        return list;
    }


        public static void main(String[] args) {
            // reading names.txt
                File namesFile = new File("names.txt");
    try
    {
      // creating scanning object on file object
                  Scanner reader = new Scanner(namesFile);
                  // reading file line by line,
                  // creating complete file string object 
                  String data = "";
                  while (reader.hasNextLine()) {
                    // reading line
                    String line = reader.nextLine();
                    // storing line in data, using , seprator
                    data = ","+line;
                  }
                  // display content 
                  // System.out.println(data);
                
                  // spliting string on , using string split method 
                  String[] names = data.split(",");
      // using strip to remove trailing spaces from names
      for(int i=0;i<names.length;i++){
        names[i] = names[i].trim();
        System.out.println(names[i]);
      }
                
                  // merges rot
      String[] sorted = mergeSort(names);
                  System.out.println("");
      // using strip to remove trailing spaces from names
      for(int i=0;i<sorted.length;i++){
        System.out.println(sorted[i]);
      }      
    }
    catch (FileNotFoundException ex)  
    {
        // insert code to run when exception occurs
        System.out.println("FIle not found");
    }
                
            
        }
}

OUTPUT IMAGE

SORTED


Related Solutions

Write a C++ or Java program that reads an input graph data from a user. Then,...
Write a C++ or Java program that reads an input graph data from a user. Then, it should present a path for the travelling salesman problem (TSP). In the assignment, you can assume that the maximum number ofvertices in the input graph is less than or equal to 20. Input format: This is a sample input from a user. 4 12 0 1 2 0 3 7 0 2 5 1 0 2 1 2 8 1 3 3 2...
Write a program that reads two strings from an input file (The first line is X,...
Write a program that reads two strings from an input file (The first line is X, the second line is Y), compute the longest common subsequence length AND the resulting string. You will need to write 2 methods 1) return LCS length in iterative function // return the length of LCS. L is the 2D matrix, X, Y are the input strings, m=|X|, n=|Y| int lcs_it(int **C, string X, string Y, int m, int n ) 2) return LCS resulting...
Write java program that will ask for the user for 2 input lines and print out...
Write java program that will ask for the user for 2 input lines and print out all words that occur 1 or more times on both lines (case sensitive). Write this without arrays and method. Here is a sample run: <Output> Enter two lines to process. The quick brown fox jumps over a lazy dog The fox hound outruns the lazy dog The words that occur on both lines are: The fox lazy dog
Using Java Project 2: Deduplication Write a program that reads a file of numbers of type...
Using Java Project 2: Deduplication Write a program that reads a file of numbers of type int and outputs all of those numbers to another file, but without any duplicate numbers. You should assume that the input file is sorted from smallest to largest with one number on each line. After the program is run, the output file should contain all numbers that are in the original file, but no number should appear more than once. The numbers in the...
Write a Java program that reads a list of 30 fruits from the file “fruits.txt”, inserts...
Write a Java program that reads a list of 30 fruits from the file “fruits.txt”, inserts them into a string array, and sorts the array in alphabetical order. String objects can be compared using relational operators such as <, >, or ==. For example, “abc” > “abd” is false, but “abc” < “abd” is true. Sample output: Before Sorting: Cherry, Honeydew, Cranberry, Lemon, Orange, Persimmon, Watermelon, Kiwifruit, Lime, Pomegranate, Jujube, Pineapple, Durian, Plum, Banana, Coconut, Apple, Tomato, Raisin, Mandarine, Blackberry,...
Write a program which reads an input file. It should assume that all values in the...
Write a program which reads an input file. It should assume that all values in the input file are integers written in decimal. Your program should read all integers from the file and print their sum, maximum value, minimum value, and average. Use the FileClient class here (from a previous reading) as an example. You'll need to create a file to be used as input to test your program, as well. Your program should work whether the integers are separated...
Write a C++ program that reads integers from standard input until end of file. Print out...
Write a C++ program that reads integers from standard input until end of file. Print out the largest integer that you read in, on a line by itself. Any erroneous input (something that is not an integer) should be detected and ignored. In the case where no integers are provided at all, print NO INTEGERS and stop. The whole program is under 40 lines of code. Just read from cin. Now, you need to detect non integers. In this case,...
Write a program in Java that reads a file containing data about the changing popularity of...
Write a program in Java that reads a file containing data about the changing popularity of various baby names over time and displays the data about a particular name. Each line of the file stores a name followed by integers representing the name’s popularity in each decade: 1900, 1910, 1920, and so on. The rankings range from 1 (most popular) to 1000 (least popular), or 0 for a name that was less popular than the 1000th name. A sample file...
Write a Java program to read in words from the given file “word.txt”. a. Prompt the...
Write a Java program to read in words from the given file “word.txt”. a. Prompt the user for two words b. Print out how many words in the file fall between those words c. If one of the two words is not contained in the file, print out which word is not found in the file d. If both words are not found in the file, print out a message e. Sample output: Please type in two words: hello computer...
IN JAVA Lab 10 This program reads times of runners in a race from a file...
IN JAVA Lab 10 This program reads times of runners in a race from a file and puts them into an array. It then displays how many people ran the race, it lists all of the times, and if finds the average time and the fastest time. In BlueJ create a project called Lab10 Create a class called Main Delete what is in the class you created and copy the Main class below into the file. There are 7 parts...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT