在最接近它们的内容中对int数组进行排序

时间:2016-12-11 06:49:19

标签: java sorting

如何在最接近当前数字的数组中对数组进行排序,例如

int NumList[] = {55,80,67,44,90,65}

int NumList[] = {55,65,67,80,90,44}

我尝试将其修改为修改后的冒泡排序但未通过

for(int i=1; i<NumList.length; i++){
            System.out.println(i);
            dist = Math.abs(NumList[i]-NumList[i-1]);
            for (int j = i +1; j < NumList.length; j++) {
                newdist=Math.abs(NumList[i]-NumList[j]);
                System.out.println(dist + ">" + newdist); 
                if(dist > newdist)
                {
                    temp = NumList[i];
                    NumList[i] = NumList[j];
                    NumList[j] = temp;
                    tempdist=newdist;
                    if(dist>tempdist){
                        dist=tempdist;
                    }
                    System.out.println("yes");
                }
                else
                    System.out.println("no");
            }

数组中的第一个int不会改变位置,因为它将是参考点

1 个答案:

答案 0 :(得分:0)

将算法的结果放入另一个数组中:

Var orderedArray = [] ;
for(int i=1; i<NumList.length; i++){
            System.out.println(i);
            dist = Math.abs(NumList[i]-NumList[i-1]);
            for (int j = i +1; j < NumList.length; j++) {
                newdist=Math.abs(NumList[i]-NumList[j]);
                System.out.println(dist + ">" + newdist); 
                if(dist < newdist)
                {
                    orderedArray.push(numList(i));

  }
                    System.out.println("yes");
                }
                else
                    System.out.println("no");
            }