Towards the bottom of my program I am trying to convert the selection sort algorithm that I had from an array to ArrayList. Those two lines that are producing errors were previously a[indexOfMin] = a[startIndex];
and a[startIndex] = min;
. I tried changing them to a.get(indexOfMin) = a.get(startIndex);
and a.get(startIndex) = min;
but that does not compile. Thank you for any and every bit of help!
class SortDouble
{
public static void main(String[] args)
{
int n = 10;
ArrayList<Double> a = new ArrayList<Double>();
Random r = new Random();
for (int i = 0; i < n; i++)
a.add(r.nextDouble());
selectionSort(a);
for (int i = 0; i < n; i++)
System.out.println(a.get(i));
}
public static void selectionSort(ArrayList<Double> a)
{
int n = 10;
for (int startIndex = 0; startIndex < n - 1; startIndex++)
{
double min = a.get(startIndex);
int indexOfMin = startIndex;
for (int j = startIndex + 1; j < n; j++)
if (a.get(j) < min)
{
min = a.get(j);
indexOfMin = j;
}
a.get(indexOfMin) = a.get(startIndex); // error here
a.get(startIndex) = min; // error here
}
}
}```
To update the value at a specific index in a Arraylist, we use set method.
Change the two lines which were causing error to:
a.set(indexOfMin, a.get(startIndex)); // a[indexOfMin] = a[startIndex];
a.set(startIndex, min); // error here // a[startIndex] = min;