java中双精度的默认写法_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

{

smallest = i;

for (j = 1; j

{

if (arr[j]

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

{

smallest = i;

for (j = 1.0; j

{

if (arr[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;

}

}

如您所见,您仍然具有双精度作为参数,并且临时值和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

标签:java,arrays,sorting

来源: https://codeday.me/bug/20190528/1168391.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值