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

Part A.1 Do a selection sort using the random number generator. Your program ask

ID: 3556148 • Letter: P

Question

Part A.1 Do a selection sort using the random number generator. Your program asks the size of data and the range of data (smallest int and the largest int). Then you generate the number of data within the range of the data. You write the data into a file as shown below.


Program Sorting> Please enter the size of data: 1000
Program Sorting> Please enter the smallest value:1
Program Sorting> Please enter the largest value:10000
Program Sorting> Please enter the name of data file: data1


Then your program produces 1000 integer ranging from 1to 10000 in the array and then sort them in ascending order and then print the result into data.txt file. (You may list integers separated by space or new line)
Part A.2 Now you implement two search methods

Explanation / Answer

Hi,

I have code Part A and it works exactly as required with comments so that it would help you understand the flow of the program. Could you post Part B as another question as it is quite lengthy as you have to read from a file into an array and then search using linear and binary search.

CODE :

import java.io.*;
import java.util.Scanner;


public class ProgramSorting {
  
  
//used to Sort Array using Selection sort algorithm
static int[] sortArray(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;
}
return arr;
}
public static void main(String[]args)
{
int dataSize,smallestValue,largestValue;
String filename;
Scanner input=new Scanner(System.in);
System.out.print("Please enter the size of data: ");
dataSize=input.nextInt();
System.out.print("Please enter the smallest value: ");
smallestValue=input.nextInt();
System.out.print("Please enter the largest value: ");
largestValue=input.nextInt();
System.out.print("Please enter the the name of the file: ");
  
//will save file to D Drive. If you need to set to C,Just replace D with C.
filename="D:\"+input.next()+".txt";
  
//declaring array to hold values
int arr[]=new int[dataSize];
  
//generating random number and stroing in array
for(int i=0;i<dataSize;i++)
{
arr[i] = smallestValue + (int)(Math.random()*largestValue);
}
  
//calling sort method
arr=sortArray(arr);
  
//Writing to File
try
{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < arr.length; i++)
{
outputWriter.write(Integer.toString(arr[i]));
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();   
}
catch(IOException ex) {System.out.print(ex.getMessage());}
System.out.println("Data is sorted and saved to file "+filename);
}

}