import java.util.Random; ? public class ArrayNum2 { public static void main(Stri
ID: 3575749 • 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 5 Program 2 ArrayNum2: What coding changes would need to sort the numbers in descending order, that is the largest number first, the smallest number last?Explanation / Answer
A very small modification needed to sort the elements in descending order.
In the selectionSort function at "If condition" folowing changes need to be done.
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] >(greater than used instead of less than) array[index])
index = x;
int maximum = array[index];
array[index] = array[i];
array[i] = maximum;
}
//returns the sorted array to where this method was called in the main method
return array;
}
This modification will results to the descending order that is biggest number first and smallest number last of the list, using selection sort.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.