【发布时间】:2014-10-06 17:10:39
【问题描述】:
您好,我正在尝试创建一个查找数组模式的方法。为此,我首先需要创建一个将列表从最小到最大排序的方法,但我不确定我首先做错了什么
public class Mode {
public int [] sort(int[] asd) {
int[] sorted = new int[10];
for (int i = 0; i < asd.length; i++) {
for (int j = 1; j < asd.length; j++) {
if ( (asd[i] > asd[j]) && (i != j) ) {
int temp = asd[j];
asd[j] = asd[i];
asd[i] = asd[temp];
}
else
continue;
}
}
return sorted;
}
public static void main(String[] args) {
Mode list1 = new Mode();
int[] array = {3,2,5,4,1,1,1,1,10,9};
int[] potato = list1.sort(array);
for (int i = 0; i < potato.length; i++)
System.out.print(potato[i]);
}
}
当我运行它时,我得到 0000000000 作为输出。我认为该方法有问题,因为我返回了一个已初始化但没有放入任何内容的数组。我如何(在我的嵌套 for 循环中)添加排序数组中的每个数字?
【问题讨论】:
-
asd[i] = asd[temp];应该是asd[i] = temp; -
您正在就地排序数组
asd,但随后返回初始化为零的sorted。尝试将数组asd复制到sorted,然后对数组sorted进行排序。 -
哦,好吧,我做到了,但仍然没有做得很好。我还将 return 更改为 return asd 而不是 sorted
-
@vikingsteve 不确定你的意思