Please write this Java program as simple as possible and with comments throughou
ID: 3730209 • Letter: P
Question
Please write this Java program as simple as possible and with comments throughout explaining what is happening. Thank you!
Program 3 (30 points)l: 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 in the main method (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
Explanation / Answer
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("List Before sorting: ");
System.out.println(Arrays.toString(names));
selectionSort(names);
System.out.println("List After sorting: ");
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: bbb
Enter Name 2: sss
Enter Name 3: eee
Enter Name 4: rr
Enter Name 5: adaas
List Before sorting:
[bbb, sss, eee, rr, adaas]
List After sorting:
[adaas, bbb, eee, rr, sss]
Do you want to continue(y or n):