我正在尝试对双打数组进行合并排序,但是出现错误。我需要你们的帮助。
import java.util.Arrays;
class MergeSort {
public static void main(String args[]) {
MergeSort ob = new MergeSort();
double nums[] = { 1.1, 1.2, 1.3, 2.2, 1.4, 2.3, 1.5, 9.8, 7.3, 7.7, 5.2, 5.1, 9.9, 4.1, 4.3, 4.2 };
System.out.println("Original Array:");
System.out.println(Arrays.toString(nums));
ob.sort(nums, 0, nums.length - 1);
System.out.println("Sorted Array:");
System.out.println(Arrays.toString(nums));
}
void merge(double nums[], int left, int m, int right) {
int n1 = m - left + 1;
int n2 = right - m;
int Left_part_arra[] = new int[n1];
int Right_part_arra[] = new int[n2];
for (int i = 0; i < n1; ++i)
Left_part_arra[i] = nums[left + i];
for (int j = 0; j < n2; ++j)
Right_part_arra[j] = nums[m + 1 + j];
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (Left_part_arra[i] <= Right_part_arra[j]) {
nums[k] = Left_part_arra[i];
i++;
} else {
nums[k] = Right_part_arra[j];
j++;
}
k++;
}
while (i < n1) {
nums[k] = Left_part_arra[i];
i++;
k++;
}
while (j < n2) {
nums[k] = Right_part_arra[j];
j++;
k++;
}
}
void sort(double nums[], int left, int right) {
if (left < right) {
int m = (left + right) / 2;
sort(nums, left, m);
sort(nums, m + 1, right);
merge(nums, left, m, right);
}
}}
我正在使用eclipse进行编码,而在此部分上我得到了红色下划线,我只是加了** **来强调。我尝试对其进行强制转换,但小数位数变为0。
for (int i = 0; i < n1; ++i)
Left_part_arra[i] = **nums[left + i];**
for (int j = 0; j < n2; ++j)
Right_part_arra[j] = **nums[m + 1 + j];**
提前谢谢!
答案 0 :(得分:0)
将代码更改为:
double Left_part_arra[] = new double[n1];
double Right_part_arra[] = new double[n2];
for (int i = 0; i < n1; ++i)
Left_part_arra[i] = nums[left + i];
for (int j = 0; j < n2; ++j)
Right_part_arra[j] = nums[m + 1 + j];
这给出了输出:
Original Array:
[1.1, 1.2, 1.3, 2.2, 1.4, 2.3, 1.5, 9.8, 7.3, 7.7, 5.2, 5.1, 9.9, 4.1, 4.3, 4.2]
Sorted Array:
[1.1, 1.2, 1.3, 1.4, 1.5, 2.2, 2.3, 4.1, 4.2, 4.3, 5.1, 5.2, 7.3, 7.7, 9.8, 9.9]
附带说明:尝试遵守Java变量命名约定,变量的首字母应小写。类/接口的首字母大写,常量完全用大写。 https://www.oracle.com/technetwork/java/codeconventions-135099.html