【问题标题】:Selection sort for doubles in javajava中双打的选择排序
【发布时间】: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,将smallestijdouble转换为int。

标签: java arrays sorting


【解决方案1】:

问题是您还使用 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。例如,当我们有一个字符串数组时,我们仍然使用整数作为索引:

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

【讨论】:

  • 好的,感谢您的深入解释!我会在允许的时候给你一张绿色支票
  • +1,但我想你也会解释一下 for 循环需要语句中的所有内容都具有相同的类型。
【解决方案2】:

你为什么把 for 循环改成双精度循环?

for (i = 0.0;i<arr.length - 1.0;i++)

它仅适用于数组索引的int

【讨论】:

  • 我想让它与双打兼容,一切都必须是双打
  • @homidhomi4 不,只保留你之前的 sn-p 中的 for 循环。
  • 不,如果 for 语句中的所有内容都是双倍的,for 循环也可以正常工作。
【解决方案3】:

您必须使用下标值作为 int 签出。像这样使用

int i = 0,j =0,smallest = 0;

使用这些访问数组值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多