有没有办法可以将 a[indexOfMin] = a[startIndex] 转换为 ArrayList 形式?我似乎无法正确地这样做
Is there a way I can convert a[indexOfMin] = a[startIndex] into ArrayList form? I can't seem to properly do so
在我的程序的底部,我试图将我拥有的选择排序算法从数组转换为 ArrayList。产生错误的这两行以前是 a[indexOfMin] = a[startIndex];
和 a[startIndex] = min;
。我尝试将它们更改为 a.get(indexOfMin) = a.get(startIndex);
和 a.get(startIndex) = min;
但无法编译。感谢您提供的所有帮助!
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
}
}
}```
要更新 Arraylist 中特定索引处的值,我们使用 set 方法。
将导致错误的两行更改为:
a.set(indexOfMin, a.get(startIndex)); // a[indexOfMin] = a[startIndex];
a.set(startIndex, min); // error here // a[startIndex] = min;
在我的程序的底部,我试图将我拥有的选择排序算法从数组转换为 ArrayList。产生错误的这两行以前是 a[indexOfMin] = a[startIndex];
和 a[startIndex] = min;
。我尝试将它们更改为 a.get(indexOfMin) = a.get(startIndex);
和 a.get(startIndex) = min;
但无法编译。感谢您提供的所有帮助!
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
}
}
}```
要更新 Arraylist 中特定索引处的值,我们使用 set 方法。
将导致错误的两行更改为:
a.set(indexOfMin, a.get(startIndex)); // a[indexOfMin] = a[startIndex];
a.set(startIndex, min); // error here // a[startIndex] = min;