Write a computer program in java using Selection Sort t hat prompts the user for
ID: 3606421 • Letter: W
Question
Write a computer program in java using Selection Sort that prompts the user for one number, n for the number of items in the array to sort, and create and sort 1000 arrays of this size timing the run to get an average time to sort an array of this size. Then do the following:
Initiate a variable running_time to 0
Create a for loop that iterates 1000 times.
In the body of the loop,
Create an array of n random integers
Get the time and set this to start-time. You will have to figure out what the appropriate command is in the programming language you are using to find the time
Use bubble sort to sort the array
Get the time and set this to end-time
Subtract start-time from end-time and add the result to total_time
Once the program has run, note
The number of items sorted
The average running time for each array (total_time/1000)
Repeat the process six times, using 50, 250 and 500 as the size of the array for each of the two algorithms.
Explanation / Answer
import java.util.Random;
public class Main {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int[] Array = generateArray();
System.out.println("Unsorted Array:");
printArray(Array);
sortArray(Array);
System.out.println("Sorted data:");
printArray(Array);
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(" Time taken is : "+totalTime);
}
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.