为什么这个数组不能正常工作[重复]

时间:2021-12-27 21:28:14

This question already has an answer here:

这个问题在这里已有答案:

I will in this method descending order number integer

我将在这个方法中降序数整数

package sortarray;

public class start {

    public static void main(String[] args) {

        int [] numb={10,12,8,6,2};

        sortarray(numb);
    }

    public static void sortarray(int [] input){

        int max=input[0];

        int [] sortmax=input;//i don't know how this array sortmax initialized first

        for (int i=0;i<input.length;i++)
            if(max<input[i]){
                max=input[i];

                sortmax[i]=max;//this array is not work 
            }

        for (int j=0;j<sortmax.length;j++)
            System.out.print(" "+sortmax[j]);
    }           

}

but into this method, (sortmax) is not work why?

但是进入这种方法,(sortmax)不起作用为什么?

2 个解决方案

#1


1  

I understand you want to keep some kind of history of max'es?

我知道你想保留一些max'es的历史吗?

sortmax is just referencing to your input array, everything you do on sortmax you do on input. You need to do this:

sortmax只是引用你的输入数组,你在sortmax上做的所有事情都是你输入的。你需要这样做:

int[] sortmax = new int[input.length];

int [] sortmax = new int [input.length];

instead of int[] sortmax = input;.

而不是int [] sortmax = input;。

#2


0  

You can always use the Arrays.sort() for this, but if the goal is to learn sorting, a brute force (slow for large vectors) sorter could look like this:

你可以随时使用Arrays.sort(),但如果目标是学习排序,那么蛮力(大型向量的速度慢)分拣机可能如下所示:

public void sort(int[] array){
   int[] tempArray = new int[array.length]
   int max;
   int index;
   for(int k = 0; k < array.length; k++){
     for(int i = 0; i < array.length; i++){
       if(max < array[i]){
         max = array[i];
         index = i;
        }
     }
     tempArray[k] = array[index];
     array[index] = Integer.MIN_VALUE;
   }
   array = tempArray;
}

#1


1  

I understand you want to keep some kind of history of max'es?

我知道你想保留一些max'es的历史吗?

sortmax is just referencing to your input array, everything you do on sortmax you do on input. You need to do this:

sortmax只是引用你的输入数组,你在sortmax上做的所有事情都是你输入的。你需要这样做:

int[] sortmax = new int[input.length];

int [] sortmax = new int [input.length];

instead of int[] sortmax = input;.

而不是int [] sortmax = input;。

#2


0  

You can always use the Arrays.sort() for this, but if the goal is to learn sorting, a brute force (slow for large vectors) sorter could look like this:

你可以随时使用Arrays.sort(),但如果目标是学习排序,那么蛮力(大型向量的速度慢)分拣机可能如下所示:

public void sort(int[] array){
   int[] tempArray = new int[array.length]
   int max;
   int index;
   for(int k = 0; k < array.length; k++){
     for(int i = 0; i < array.length; i++){
       if(max < array[i]){
         max = array[i];
         index = i;
        }
     }
     tempArray[k] = array[index];
     array[index] = Integer.MIN_VALUE;
   }
   array = tempArray;
}