java - Java 将两个数组合并为一个并对其进行排序
问题描述
我的任务是将两个数组连接成一个数组并对其进行排序。我已经连接了数组,但无法对其进行排序。
我的想法:创建一个新数组。在通过循环的连接数组中,找到最小的元素,将其推送到一个新数组中,最后使其成为最大数。但是,这种方法行不通。
我的代码:
public class Concat_arrays {
public static void main(String[] args) {
int[] a1 = {4, 5, 3, 2, 1};
int[] a2 = {10, 29, 0};
int[] a3 = new int[a2.length+a1.length];
int index = 0;
for (int i = index; i<a1.length; i++) {
a3[i] = a1[i];
index++;
}
int indexA2 = 0;
while (indexA2<a2.length) {
a3[index] = a2[indexA2];
index++;
indexA2++;
}
int[] a4 = new int[a3.length];
for (int i = 0; i<a3.length; i++) {
int min_index = getMin(a3);
a4[i] = a3[min_index];
a3[min_index] = 999999;
}
}
public static int getMin(int[] array) {
int min_element = 0;
int min_element_index = 0;
for (int i = 0; i<array.length; i++) {
if (min_element>=array[i]) {
min_element_index = i;
}
}
return min_element_index;
}
输出:
4
999999
999999
999999
999999
999999
999999
999999
解决方案
你的想法是正确的,但你的getMin
方法是不正确的。我在下面更新了它。(你的想法可以改进)
public static int getMin(int[] array) {
int min_element = Integer.MAX_VALUE; // Do not set it to 0 since there might be elements that has the value of 0
int min_element_index = 0;
for (int i = 0; i < array.length; i++) {
if (min_element >= array[i]) {
min_element = array[i]; // You have to update your minimum element
min_element_index = i;
}
}
return min_element_index;
}
同样在这部分中a3[min_index] = 999999;
最好将其设置为,a3[min_index] = Integer.MAX_VALUE;
因为可能存在大于 999999 的元素。
推荐阅读
- python - send_message() 缺少 1 个必需的位置参数:“消息”
- javascript - 将状态从父级传递给子级
- data-structures - .h5 数据集操作的更好方法?
- java - IntelliJ 2021.2.2 在编译程序时给出错误“java:错误:无效的源版本:18”
- software-design - 究竟什么是前端模型?
- python - 为什么查询返回一个数字而不是行值?
- android - 为什么我在 NativeActivity 中看不到我的布局?
- c# - ReactiveUI.NET - 使用交互
从 ViewModel 通知用户正在进行的工作 - javascript - 我可以将 Jest Mocks 放在不同的文件中并将其导入我的测试文件吗?
- java - 添加 Docker 映像后工作流显示错误