Revise SelectionSortjava listing 78 page 270 to sort a list

Revise SelectionSort.java listing 7.8, page 270, to sort a list of students\' names (as strings) (name it SortStrings). Design the main method to prompt the user to enter the list size, read the student names into an array of strings, print the array before sorting (use the label “List Before Sorting:”, pass the array to the sort method, and finally print the sorted array (use the label “List After Sorting:”). No printing in the sort method. Design the main method of your program to handle all input and output and to allow the user to re-run the program with different sets of inputs. Document your code and organize the output using appropriate formatting techniques.

Solution

SortStrings.java


import java.util.Arrays;
import java.util.Scanner;


public class SortStrings {

   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       while(true){
       System.out.println(\"Enter the list size: \");
       int n = scan.nextInt();
       scan.nextLine();
       String names[] = new String[n];
       for(int i=0; i<names.length; i++){
           System.out.print(\"Enter Name \"+(i+1)+\": \");
           names[i] = scan.nextLine();
       }
       System.out.println(\"Before Asorting, Names are: \");
       System.out.println(Arrays.toString(names));
       selectionSort(names);

System.out.println(\"After Asorting, Names are: \");
       System.out.println(Arrays.toString(names));
       System.out.println(\"Do you want to continue(y or n): \");
       char ch = scan.next().charAt(0);
       if(ch == \'n\' || ch ==\'N\'){
           break;
       }
       }
   }

   public static void selectionSort(String arr[]){
       for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j].compareTo(arr[index]) < 0)
index = j;
  
String str = arr[index];
arr[index] = arr[i];
arr[i] = str;
}
   }

}

Output:

Enter the list size:
5
Enter Name 1: Suresh
Enter Name 2: Sekhar
Enter Name 3: Anshu
Enter Name 4: Revathi
Enter Name 5: Murapaka
Before Asorting, Names are:
[Suresh, Sekhar, Anshu, Revathi, Murapaka]
After Asorting, Names are:
[Anshu, Murapaka, Revathi, Sekhar, Suresh]
Do you want to continue(y or n):
n

Revise SelectionSort.java listing 7.8, page 270, to sort a list of students\' names (as strings) (name it SortStrings). Design the main method to prompt the use
Revise SelectionSort.java listing 7.8, page 270, to sort a list of students\' names (as strings) (name it SortStrings). Design the main method to prompt the use

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site