import java.util.Random; ? public class ArrayNum2 { public static void main(Stri
ID: 3575750 • Letter: I
Question
import java.util.Random;
?
public class ArrayNum2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// creates new array with 20 elements
int [] array = new int[20];
//random seed of 10
Random r = new Random(10);
//assigns random numbers 1-50 to the 20 elements in the array
for (int i = 0; i < array.length; i++){
array[i] = r.nextInt(50) + 1;
System.out.println(array[i]+ " ");
}
// calls the sorted_array method
int [] sorted_array = selectionSort(array);
//prints the array that was returned from the selectionSort method
System.out.println("The sorted array is " );
for (int i = 0; i < array.length -1; i++) {
System.out.print(array[i] + " ");
}
}
public static int[] selectionSort(int [] array) {
for (int i = 0; i < array.length -1; i++) {
int index = i;
//loops through each element in array and if element is less than element it is being compared to, it is placed before it
for (int x = i + 1; x < array.length; x++)
if (array[x] < array[index])
index = x;
int minimum = array[index];
array[index] = array[i];
array[i] = minimum;
}
//returns the sorted array to where this method was called in the main method
return array;
}
}
QUESTION 6 Program 2 Array Num2 Why does line 30 have nt X i 1, versus say int xi i or int x- 1?Explanation / Answer
Explanation
Here before the loop value of i which is 0 is stored in index. Then loop starts from i+1 which is 0+1=1 because we need to compare the array[first] element with array[zero] element. If we found array[first] smaller than array[zero] then we do the swap of the two values using third temporary variable.
Also we use i+1=1 instead of direct x=1 because we have an outer loop runing on i. If we keep it as x=1 then it will always compare it with the first element once inner loop is executed.
I have added the comments in the selectionSort funtion as well.
public static int[] selectionSort(int [] array) {
for (int i = 0; i < array.length -1; i++) {
int index = i; // Here 0 is stored in Index so that we can use this index to compare with zeroth element
//loops through each element in array and if element is less than element it is being compared to, it is placed before it
for (int x = i + 1; x < array.length; x++) // Here we start from i+1 which is 0+1=1 because we already have stored 0 in index variable so that we can compare Zero element with first element in the loop.
if (array[x] < array[index]) // Here array of first element is check with array of 0 element and if its smaller then we do the swap.
index = x;
int minimum = array[index]; //using minimum as temporary variable.
array[index] = array[i];
array[i] = minimum;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.