java - Int 数组排序本身
问题描述
import java.util.ArrayList;
public class Paaohjelma {
public static int pienin(int[] taulukko) {
int temp, size;
size = taulukko.length;
for(int i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(taulukko[i]>taulukko[j]){
temp = taulukko[i];
taulukko[i] = taulukko[j];
taulukko[j] = temp;
}
}
}
return taulukko[0];
}
public static int pienimmanIndeksi(int[] taulukko) {
ArrayList<Integer> tauli = new ArrayList<>();
for (int i : taulukko) {
tauli.add(i);
}
return tauli.indexOf(Paaohjelma.pienin(taulukko));
}
public static int pienimmanIndeksiAlkaen(int[] taulukko, int aloitusIndeksi) {
// this methods should get the index of smallest value starting from specified index
int[] tempTauli = taulukko;
tempTauli = new int[tempTauli.length - aloitusIndeksi];
// this gets the right values to temporary array
if (aloitusIndeksi > 0) {
int index = 0;
int indexTauli = 0;
for(int value : taulukko) {
if(index >= aloitusIndeksi) {
tempTauli[indexTauli] = taulukko[index];
indexTauli++;
}
index++;
}
}
// values added are automatically sorted from smallest to largest?
// this shouldn't be, array should be 5, 99, 3, 12 but is shown as 3, 5, 12, 99
for(int inty : tempTauli) {
System.out.println(inty);
}
// get the index of smallest value in array
// index is 0 should be 2
int index = Paaohjelma.pienimmanIndeksi(tempTauli);
// return index of smallest value (add starting index to get the index of smallest value in the original array when starting from specified index)
return index+aloitusIndeksi;
}
public static void main(String[] args) {
// test code
int[] taulukko = {3, 1, 5, 99, 3, 12};
int minIndex = Paaohjelma.pienimmanIndeksi(taulukko);
System.out.println("Pienin: " + Paaohjelma.pienin(taulukko));
System.out.println("Pienimmän indeksi: " + minIndex);
System.out.println(Paaohjelma.pienimmanIndeksiAlkaen(taulukko, 2));
}
}
你好!我正在为学校做一些编程课程的工作,并且已经在这个特定的部分停留了几个小时。所以我决定最好让其他人看看并提供一些说明为什么我解决这个问题的方法不起作用。
应该发生什么:类方法 PienimmanIndeksiAlkaen 应该从指定的索引开始返回提供的 int 数组中最小值的索引。
我遇到的主要问题是数组似乎会自动排序,我不知道是什么原因造成的。我已经评论了代码的相关部分,如果有人能解释为什么会发生这种情况以及可以采取哪些措施来防止这种情况发生,我会非常高兴。
解决方案
您的数组排序的原因是当您调用
System.out.println("Pienin: " + Paaohjelma.pienin(taulukko));
你对数组进行排序。
当你将数组传递给这个函数时,你实际上传递的不是数组的值,而是指向数组的指针——数组在内存中的地址。这就是按值传递参数和按引用传递参数的区别。
如何知道值是按值传递还是按引用传递?根据经验:
原始值 - 即 int、double 等将按值传递 - 它们的值将被复制并传递给函数。
任何其他类型,即数组和类,将通过引用传递 - 内存中值的地址将传递给函数,因此函数内部值的任何更改也会在函数结束时影响它。
推荐阅读
- ios - 修复错误->“无法将'SecondViewController'类型的值转换为'FirstViewController'”
- dart - 如何在 Column 类中将小部件与顶部对齐?
- javascript - 单击屏幕上的任意位置以隐藏没有 Jquery 的通知栏
- machine-learning - 是否可以仅通过仅向其提供一个类的输入来训练二元分类神经网络?
- python-3.x - Py4JJavaError:调用 o26.parquet 时出错。(读取 Parquet 文件)
- c# - InvalidOperationException:匹配了多个处理程序。以下处理程序匹配路由数据并满足所有约束:
- leaflet - 在 Leaflet 中有效地将路段可视化为热图
- jpa - 如何使用 JPA Criteria 计算查询中的行数?
- php - 使用 nginix 未在 docker 中加载 css
- apache-spark - 任务不可序列化异常使用火花 KeyValueGroupedDataset 并且每个组在窗口中聚合时