gpt4 book ai didi

java - java中 double 的选择排序

转载 作者:搜寻专家 更新时间:2023-11-01 02:05:48 25 4
gpt4 key购买 nike

我之前为整数编写了选择排序方法,但现在我正在处理一个 double 组。我已经尝试将变量更改为 double ,但我仍然收到“无法从 double 转换为整数”。感谢任何帮助,谢谢!

//Original selection sort for ints
public static void selectionSort (int... arr)
{
int i = 0, j = 0, smallest = 0;
int temp = 0;

for (i = 0;i<arr.length - 1;i++)
{
smallest = i;
for (j = 1; j<arr.length - 1; j++)
{
if (arr[j]<arr[smallest])
smallest = j;
}
temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;

}
}

//Attempted selection sort with doubles
public static void selectionSort (double...arr )
{
double i = 0.0, j = 0.0, smallest = 0.0;
double temp = 0.0;

for (i = 0.0;i<arr.length - 1.0;i++)
{
smallest = i;
for (j = 1.0; j<arr.length - 1.0; j++)
{
if (arr[j]<arr[smallest]) //error here with smallest and j
smallest = j;
}
temp = arr[smallest]; //error here with smallest
arr[smallest] = arr[i]; //error here with smallest and i
arr[i] = temp; //error here with i

}
}

最佳答案

问题是您还使用了 double 来索引数组。所以试试这个:

public static void selectionSort (double...arr)
{
int i = 0, j = 0, smallest = 0;
double temp = 0.0;

for (i = 0; i < arr.length - 1; i++)
{
smallest = i;
for (j = 1; j < arr.length - 1; j++)
{
if (arr[j] < arr[smallest])
smallest = j;
}
temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
}
}

如您所见,您仍然有 double 作为参数,temp-value 和 arr-array 也仍然是 double ,但是用于数组是整数。

索引总是整型的。例如,当我们有一个字符串数组时,我们仍然使用 int 作为索引:

String[] sArray = {
"word1",
"word2",
"word3"
}
int index = 1;
String result = sArray[index]; // As you can see we use an int as index, and the result is a String
// In your case, the index is still an int, but the result is a double

关于java - java中 double 的选择排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34023517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com