KG
Answered
Write a Java method as well as any facilitator methods needed to perform a sort on an array of whole numbers in descending order.
On Jun 22, 2024
/**
Precondition: The array has values.
Action: Sorts a so that a[0] >= a[1] >= ... >= a[a.length]
*/
public static void selectionSortint[] a)
{
int indexOfLargest;
forint i=0;i < a.length;++i)
{
indexOfLargest = LargestIndexi,a);
swapi,indexOfLargest,a);
}
}
/**
Returns the index of the largest value among
a[start],a[start + 1],...a[a.length-1]
*/
private static int LargestIndexint start,int[] a)
{
int max = a[start];
int indexOfMax = start;
forint i=start + 1;i < a.length;i++)
{
ifa[i] > max)
{
max = a[i];
indexOfMax = i;
}
}
return indexOfMax;
}
/**
Precondition: i and j are legal indices for the array a.
Postcondition: Values of a[i] and a[j] have been interchanged
*/
private static void swapint i,int j,int[] a)
{
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}