Create a program called InsertionSort.java that implements the Insertion Sort algorithm. The program should be able to do the following:
-accepts two command line parameters, the first one is an integer specifying how many strings to be sorted, and the second one is the path to a text file containing the values of these strings, one per line.
-reads the strings from the text file into an array of strings. sorts the strings using InsertionSort, and then print out a sorted version of those input strings with one string per line.
The implementation should follow the given pseudo code/algorithm description.

Respuesta :

Answer:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class InsertionSort {

   public static void insertionSort(String[] array) {

       int n = array.length;

       for (int i = 1; i < n; i++)

       {

           String temp = array[i];

           int j = i - 1;

           while (j >= 0 && temp.compareTo(array[j]) < 0)

           {

               array[j + 1] = array[j];

               j--;

           }

           array[j+1] = temp;

       }

   }

   public static void main(String[] args) {

       if (args.length == 2) {

           int n = Integer.parseInt(args[0]);

           File file = new File(args[1]);

           try {

               Scanner fin = new Scanner(file);

               String[] strings = new String[n];

               for (int i = 0; i < n; i++) {

                   strings[i] = fin.nextLine();

               }

               insertionSort(strings);

               for (int i = 0; i < n; i++) {

                   System.out.println(strings[i]);

               }

               fin.close();

           } catch (FileNotFoundException e) {

               System.out.println(file.getAbsolutePath() + " is not found!");

           }

       } else {

           System.out.println("Please provide n and filename as command line arguments");

       }

   }

}

Explanation: