Program 3 (30 points) Revise SelectionSort,java listing 7.8, page 270, to sort a
ID: 3606616 • Letter: P
Question
Program 3 (30 points) 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 techniquesExplanation / Answer
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[] Array = generateArray();
System.out.println("Unsorted Array:");
printArray(Array);
sortArray(Array);
System.out.println("Sorted data:");
printArray(Array);
}
private static void sortArray(int[] Array) {
for (int i=0; i<Array.length-1; i++) {
for (int j=i+1; j<Array.length; j++) {
if (Array[i] > Array[j]) {
int temp = Array[i];
Array[i] = Array[j];
Array[j] = temp;
}
}
}
}
private static int[] generateArray() {
Random random = new Random();
int[] Array = new int[10];
for (int i=0; i<Array.length; i++) {
Array[i] = random.nextInt(100);
}
return Array;
}
private static void printArray(int[] Array) {
for (int i=0; i<Array.length; i++) {
System.out.print(Array[i]);
System.out.print(", ");
}
System.out.println();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.