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

Using the System class introduced in our lab session and the selection sort prog

ID: 3861789 • Letter: U

Question

Using the System class introduced in our lab session and the selection sort program discussed in our lecture to report the elapsed time when we use selection sort program to sort n integers, where n is an integral number input by the user of your program and each integer is between 0 and 99999 inclusive. The following is a sample run of your program.

Input a number (at least 1000):

4000

Selection sort needs 60 milliseconds to sort 4000 integers.

Continue ? (Yes/No) Yes

Input a number (at least 1000):

10000

Selection sort needs 310 milliseconds to sort 10000 integers.

Continue ? (Yes/No) No

Explanation / Answer

SelectSortTime.java

import java.util.Random;
import java.util.Scanner;


public class SelectSortTime {

  
   public static void main(String[] args) {
   String s = "Yes";
Scanner scan =new Scanner(System.in);
while(s.equalsIgnoreCase("Yes")){
System.out.println("Input a number (at least 1000): ");
int n = scan.nextInt();
int a[] = new int[n];
Random r = new Random();
for(int i=0; i<n; i++){
   a[i]=r.nextInt(100000);
}
long startTime = 0;
long lastTime = 0;
startTime = System.currentTimeMillis();
selectionSort(a);
lastTime = System.currentTimeMillis();
System.out.println("Selection sort needs "+(lastTime - startTime)+" milliseconds to sort "+n+" integers.");
System.out.println("Continue ? (Yes/No): ");
s=scan.next();
}
   }
   public static void selectionSort(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;
}
   }
}

Output:

Input a number (at least 1000):
4000
Selection sort needs 8 milliseconds to sort 4000 integers.
Continue ? (Yes/No):
yes
Input a number (at least 1000):
10000
Selection sort needs 31 milliseconds to sort 10000 integers.
Continue ? (Yes/No):
yes
Input a number (at least 1000):
50000
Selection sort needs 732 milliseconds to sort 50000 integers.
Continue ? (Yes/No):
no

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