- #1
blue_soda025
- 26
- 0
So, I have to create a program that makes a new array with 20 slots, then it asks you to enter a value into each index, which I have here:
Except I have to make it so that it sorts each value from smallest to largest and print that out in the last line. I'm supposed to use selection sort for this and I'm given the code:
The problem is, I have no idea how to implement this code to my original program :/. So the question is, how do I use selection sort in that program? Any help would be appreciated.
Code:
import java.io.*;
class ArrayLoop
{
public static void main (String[] args) throws IOException
{
int[] array = new int[20];
for (int i = 0; i <= 19; i++)
{
System.out.println("Assign a value to slot " + i + ".");
array[i] = KeyIn.anInt();
}
System.out.println();
System.out.println("The values are: ");
for (int j = 0; j <= 19; j++)
{
System.out.print(array[j] + " ");
}
}
}
Except I have to make it so that it sorts each value from smallest to largest and print that out in the last line. I'm supposed to use selection sort for this and I'm given the code:
Code:
static void selection_sort(int a[])
{
int i, min;
for (i = 0; i < a.length; i++)
{
min = find_minimum(a, i);
swap(a, i, min);
}
}
static int find_minimum (int a[], int i)
{
int j; min = i;
for (j = i + 1; j < a.length; j++)
if (a[j] < a[min])
min = j;
return min;
}
static void swap(int a[], int i, int j)
{
int hold = a[i];
a[i] = a[j];
a[j] = hold;
}
The problem is, I have no idea how to implement this code to my original program :/. So the question is, how do I use selection sort in that program? Any help would be appreciated.