[英]Selection sort for doubles in java
我之前已经为int编写了选择排序方法,但是现在我正在处理一组双打。 我已经尝试将变量更改为双精度,但我仍然得到“无法从double转换为int”。 任何帮助表示赞赏,谢谢!
//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;
}
}
正如您所看到的,仍然有双精度作为参数, temp
value和arr
-array也仍然是双精度数,但用于数组的索引是整数。
索引总是int。 例如,当我们有一个字符串数组时,我们仍然使用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
你为什么把for循环改成双打?
for (i = 0.0;i<arr.length - 1.0;i++)
它只适用于int
的数组索引。
你必须使用下标值作为int check out out。 像这样使用
int i = 0,j =0,smallest = 0;
使用这些访问数组值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.