In: Computer Science
Reverse the following selection sort to sort the items from right to left by computing the max instead of min in java. (just write the algorithm)
public class Selection{
public static void sort(Comparable[] a) {
// Sort a[] into increasing order.
int N = a.length;
// array length
for (int i = 0; i < N; i++) {
// Exchange a[i] with smallest entry in a[i+1...N).
int min = i;
// index of minimal entr.
for (int j = i+1; j < N; j++)
if (less(a[j], a[min])) min = j;
exch(a, i, min);
}
}
}
AS u already know the algorithm so simply here isthe code
for sorting in reverse direction.
class selection{
public static void main(String[] args) {
int arr[] ={121,230,71,89,12};
// main algo for reverse selection sort
int n=5;
// size of input
for(int
i=0;i<n-1;i++)
{
for(int
j=i+1;j<n;j++)
{
// here sign is changed as to calculate in opposite direction
if(arr[i]<arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");
}
}