Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program MySelection.java that reads 3 different lists from a file, sorts

ID: 3882516 • Letter: W

Question

Write a program MySelection.java that reads 3 different lists from a file, sorts them using selection sort and print the sorted list to the screen. Use the following main function, public static void main(String[] args)throws Exception { for (integral i = 1: i lessthanorequalto 3, i++) { String s = "list" + i + ".txt": int [] myarray = getList(s): System.out.println ("Current array %d: ", i): System.out.println (Arrays.toString (myarray)): SortArrayUsingSelectionSort (myArray): System.out.println ("Sorted array %d: ", i): System.out.println (Arrays.toString(myArray)): } }

Explanation / Answer

MySelection.java

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Arrays;

import java.util.Scanner;

public class MySelection {

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

for(int i=1;i<=3;i++) {

String s = "list"+i+".txt";

int[] myArray = getList(s);

System.out.printf("Current array %d. ", i);

System.out.println(Arrays.toString(myArray));

SortArrayUsingSelectionSort(myArray);

System.out.printf("Sorted array %d. ", i);

System.out.println(Arrays.toString(myArray));

}

}

public static void SortArrayUsingSelectionSort(int 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] < arr[index])

index = j;

  

int smallerNumber = arr[index];

arr[index] = arr[i];

arr[i] = smallerNumber;

}

}

public static int[] getList(String fileName) throws FileNotFoundException {

File file = new File(fileName);

Scanner scan = new Scanner(file);

int count = 0;

while(scan.hasNextInt()) {

count++;

scan.nextInt();

}

int[] arr = new int[count];

Scanner scan1 = new Scanner(file);

count = 0;

while(scan1.hasNextInt()) {

arr[count] = scan1.nextInt();

count++;

}

return arr;

}

}

Output:

Current array 1.
[3, 4, 5, 6, 7, 1, 9, 8]
Sorted array 1.
[1, 3, 4, 5, 6, 7, 8, 9]
Current array 2.
[44, 66, 22, 11, 33, 88, 77]
Sorted array 2.
[11, 22, 33, 44, 66, 77, 88]
Current array 3.
[333, 555, 777, 88, 999, 111, 222]
Sorted array 3.
[88, 111, 222, 333, 555, 777, 999]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote