[10] Create a program called SelectionSort.java that implements the Selection Sort algorithm (The Art of Computer Programming - Donald Knuth). The algorithm is as follows: The program should be able to do the following: accepts one command line parameter. The parameter specifies the path to a text file containing the integers to be sorted. The structure of the file is as follows: There will be multiple lines in the file (number of lines unknown). Each line will contain multiple integers, separated by a single whitespace. reads the integers from the text file in part a into an array of integers. sort the integers in ascending order, and then prints out a sorted version of these integers, one per line. The implementation should follow the given the pseudo code/algorithm description.

Respuesta :

Answer:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.ArrayList;

import java.util.Scanner;

public class SelectionSort {

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

      //For array

      ArrayList<Integer>array=new ArrayList<Integer>();

      //If argument found

      if(args.length>=1) {

          //File path

          Scanner sc=new Scanner(new File(args[0]));

          //Loop until end

          while(sc.hasNextLine()) {

              //Read each line and add into array

              String[] temp=sc.nextLine().split(" ");

              for(int i=0;i<temp.length;i++) {

                  array.add(Integer.parseInt(temp[i]));

              }

          }

          //Display array

          System.out.println("Display array: ");

          printArray(array);

          System.out.println("\nDisplay array after sort: ");

          sortArray(array);

          printArray(array);

      }

      //If argument not found

      else {

          System.out.println("Argument not found!!!");

      }

  }

  //Method to print array

  public static void printArray(ArrayList<Integer>array) {

      for(int i=0;i<array.size();i++) {

          System.out.println(array.get(i));

      }

  }

  //Method to sort array using straight selection sort

  public static void sortArray(ArrayList<Integer>array) {

      //Step1

      for(int j=array.size()-1;j>=1;j--) {

          int max=array.get(j);

          int index=j;

          //Step2

          for(int k=j;k>=0;k--) {

              if(max<array.get(k)) {

                  max=array.get(k);

                  index=k;

              }

          }

          //Step3

          array.set(index,array.get(j));

          array.set(j,max);

      }

  }

}

Explanation: