Java 为什么赢了';这不是分拣工作吗
好的,我写了一个方法,它应该对Java 为什么赢了';这不是分拣工作吗,java,sorting,arraylist,Java,Sorting,Arraylist,好的,我写了一个方法,它应该对ArrayList对象进行排序。而且它确实。。。某种程度上。该对象是一个由20个随机数组成的数组,在执行下面所示的代码后,我得到以下结果: [-7、-7、-7、-7、-7、-7、-7、-7、-7、13、13、13、13、27、27] public static void sortArray (ArrayList<Integer> arrayToSort) { int smallestNum; for (int j=0; j<arr
ArrayList
对象进行排序。而且它确实。。。某种程度上。该对象是一个由20个随机数组成的数组,在执行下面所示的代码后,我得到以下结果:
[-7、-7、-7、-7、-7、-7、-7、-7、-7、13、13、13、13、27、27]
public static void sortArray (ArrayList<Integer> arrayToSort)
{
int smallestNum;
for (int j=0; j<arrayToSort.size(); j++)
{
smallestNum = arrayToSort.get(j);
for (int i=j; i<arrayToSort.size(); i++)
{
if (arrayToSort.get(i)<=smallestNum)
{
smallestNum = arrayToSort.get(i);
}
}
arrayToSort.set(j, smallestNum);
}
}
公共静态无效排序(ArrayList arrayToSort)
{
int smallestNum;
对于(int j=0;j执行此行时:
arrayToSort.set(j, smallestNum);
你吹走了已经在j位置上的任何东西,然后完全失去了它,这就是为什么你看到-7被复制,直到你到达-7在原始数组中的位置。你想把最小的数字换成第j个位置,把第j个位置上的数字换成最小的数字
你真正想要的是:
public static void sortArray (ArrayList<Integer> arrayToSort)
{
int smallestNum;
int smallestPos;
for (int j=0; j<arrayToSort.size(); j++)
{
smallestNum = arrayToSort.get(j);
smallestPos = j;
for (int i=j; i<arrayToSort.size(); i++)
{
if (arrayToSort.get(i)<=smallestNum)
{
smallestNum = arrayToSort.get(i);
smallestPos = i;
}
}
arrayToSort.set(smallestPos, arrayToSort.get(j);
arrayToSort.set(j, smallestNum);
}
}
公共静态无效排序(ArrayList arrayToSort)
{
int smallestNum;
int smallestPos;
对于(int j=0;j您正在用第i个索引值替换第j个索引值。因此,它将创建一个重复条目,并且您将丢失第j个索引中包含的前一个值
也许你需要一些类似的东西:
public static void sortArray (ArrayList<Integer> arrayToSort)
{
int smallestNum;
int smallestIndex;
for (int j=0; j<arrayToSort.size(); j++)
{
smallestNum = arrayToSort.get(j);
smallestIndex = j;
for (int i=j; i<arrayToSort.size(); i++)
{
if (arrayToSort.get(i)<=smallestNum)
{
smallestNum = arrayToSort.get(i);
smallestIndex = i;
}
}
arrayToSort.set(smallestIndex, arrayToSort.get(j));
arrayToSort.set(j, smallestNum);
}
}
公共静态无效排序(ArrayList arrayToSort)
{
int smallestNum;
int smallestIndex;
对于(int j=0;j,结果对我来说是排序的。。有什么问题吗?为什么不使用集合。排序
?此外,结果对我来说是排序的。或者你想要不同的排序吗?你在j
处擦除值,并且不将其移动到任何地方。@Maroun Maroun好吧,原始数组有更多不同的数字