Question: Java Modify the sort code. Change IndexOfSmallest to IndexOfLargest but still keep the same output public class ArraySorter { public static final int MIN_SIZE =
Java
Modify the sort code. Change IndexOfSmallest to IndexOfLargest but still keep the same output
public class ArraySorter
{
public static final int MIN_SIZE = 5; // For quick sort
// SELECTION SORT
/** Sorts the first n objects in an array into ascending order.
@param a An array of Comparable objects.
@param n An integer > 0. */
public static >
void selectionSort(T[] a, int n)
{
selectionSort(a, 0, n - 1); // invoke recursive method
} // end selectionSort
public static >
void selectionSort(T[] a, int first, int last)
{
if (first < last)
{ // Place the smallest value at beginning of array:
int indexOfNextSmallest = getIndexOfSmallest(a, first, last);
swap(a, first, indexOfNextSmallest);
selectionSort(a, first + 1, last);
} // end if
} // end selectionSort
// Returns the index of the smallest value in a portion of an array.
private static >
int getIndexOfSmallest(T[] a, int first, int last)
{
T min = a[first];
int indexOfMin = first;
for (int index = first + 1; index <= last; index++)
{
if (a[index].compareTo(min) < 0)
{
min = a[index];
indexOfMin = index;
// Assertion: min is the smallest of a[first] through a[index].
} // end if
} // end for
return indexOfMin;
} // end getIndexOfSmallest
//
-------------------------------------------------------------------------------
// Swaps the array entries array[i] and array[j].
private static void swap(Object[] array, int i, int j)
{
Object temp = array[i];
array[i] = array[j];
array[j] = temp;
} // end swap
} // end ArraySorter
public class Main
{
public static void main(String[] args)
{
Integer[] array = new Integer[5];
array[0] = 5;
array[1] = 2;
array[2] = 7;
array[3] = 3;
array[4] = 23;
ArraySorter.selectionSort(array, 5);
for(int i=0; i< 5; i++)
System.out.println(i + " " + array[i]);
} // end main
}
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
