Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify the selection sort algorithm to sort an array of coins by their value. pu

ID: 3824519 • Letter: M

Question

Modify the selection sort algorithm to sort an array of coins by their value.

public class SelectionSorter
{
public static void sort(int[] a)
{
for(int i = 0; i < a.length -1; i++)
{
int minPos = minimumPosition(a,i);
ArrayUtil.swap(a, minPos, i);
}
}
private static int minimumPosition(int[] a , int from)
{
int minPos = from;
for(int i = from +1; i < a.length; i++)
{
if (a[i] < a[minPos])
{
minPos = i;
}
}
return minPos;
  
}
}

import java.util.Array;

public class SelectionSortDemo
{
public static void main(String[] args)
{
int[] a = ArrayUtil.randomIntArray(20, 100);
System.out.println(Arrays.toString(a));
  
SelectionSorter.sort(a);
System.out.println(Arrays.toString(a));
}
}

import java.util.Random;

public class ArrayUtil
{
private static Random generator = new Random();
public static int[] randomIntArray(int length, int n)
{
int [] a = new int[length];
for(int i = 0; i < a.length; i++)
{
a[i] = generator.nextInt(n);
}
return a;
}
public static void swap(int[] a , int i , int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}

Explanation / Answer

PLEASE Note that, your program is having many bugs, So I have written the code from scratch, the program creates an array of random integers and prints the sorted array.

code.java

import java.util.Scanner;

public class code
{
public static void main(String[] args)
{
   //Initialize array
   int arrsize = 20;
   int a[]=new int[arrsize];
   for (int i = 0; i< arrsize ;i++ )
   {
          a[i] = (int )(Math.random() * 100 + 1);  
   }

   // Sort Array
   for (int i = 0; i< arrsize ;i++ )
   {
       int minindex = i;
       for (int j= i ;j < arrsize ; j++ )
       {
       if(a[j] <= a[minindex])
       {
           minindex = j;
       }  
       }

       int tmp = a[i];
       a[i] = a[minindex];
       a[minindex] = tmp;
   }
   //print sorted array
   for (int i = 0; i< arrsize ;i++ )
   {
               System.out.print(a[i] + " ");
   }
       System.out.print(" ");
}

}

Sample output:

16 18 25 33 39 46 54 57 57 58 60 72 79 79 89 91 92 93 98 99

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote