【发布时间】:2015-12-01 15:06:32
【问题描述】:
我之前为整数编写了选择排序方法,但现在我正在处理一个双精度数组。我尝试将变量更改为双精度,但我仍然收到“无法从双精度转换为整数”。任何帮助表示赞赏,谢谢!
//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,将
smallest、i和jdouble转换为int。