简体   繁体   English

Java数组排序不起作用

[英]Java array sorting not work

I'm new on Java, I have array problem, I try writing array sorting method but I can't success, please correct me, I want sort array high to low: 我是Java的新手,遇到数组问题,我尝试编写数组排序方法,但无法成功,请更正我,我希望数组从高到低:

public static int[] sirala(int[] arr){
    int[] yeni = new int[arr.length];
    for(int i = 0; i< arr.length-1;i++){
        if(arr[i+1] > arr[i]){
            yeni[i] = arr[i+1];
        }
        else{
            yeni[i] = arr[i];
        }
    }
    return yeni;
}

Thanks for your help 谢谢你的帮助

Modify your method sirala like this one below.You have to use two loops inner loop will take out the largest element to the front of the array (largest number will be shifted to 0 index , 2nd largest will be shifted to to 1 index and so on...),then simply you have to assign it to the yeni array's respective element after inner loop. 像下面这样修改您的方法sirala您必须使用两个循环内部循环将取出最大的元素到数组的前面(最大的数字将移至0索引,第二个最大的移至1索引,如此on ...),然后只需在内部循环后将其分配给yeni数组的相应元素即可。

public static int[] sirala(int[] arr)
{
        int[] yeni = new int[arr.length];
        //shifting ith largest element to (i-1)th pos of arr
        for(int i = 0; i< arr.length;i++)
        {
            for(int j = i+1; j< arr.length;j++){
                if(arr[j] > arr[i]){
                    int tmp=arr[i];
                    arr[i] = arr[j];
                    arr[j]=tmp;
                }
            }
            //assigning element to new array
            yeni[i] = arr[i];
        }
        return yeni; 
}

You can try the following code.I explained how code works with comments: 您可以尝试以下代码。我解释了代码如何与注释一起使用:

public static void bubbleSort(int [] array){
    //Creating boolean value for verify that array has been sorted.
    boolean isSorted=false;

    //You should execute your method until array sorted.
    while(isSorted==false){
        //Assign true value to isSorted.
        isSorted=true;

        for(int i=0;i<array.length-1;i++){
            //if array has not been sorted yet.if statement will be executed and isSorted will become false.
            //This makes while loop executed until array sorted
            if(array[i]>array[i+1]){
                int temp=array[i];
                array[i]=array[i+1];
                array[i+1]=temp;

                isSorted=false;
            }
        }
    }

}

Here you can get it sorted in more simpler syntexed way. 在这里,您可以以更简单的合成方式对它进行排序。 If you like javascript. 如果您喜欢javascript。 Have look in this. 看看这个。

 function sort(arr){ var len = arr.length; for (var i = 0; i<=len-1; i++){ for(var j = i+1; j<=len-1; j++){ if(arr[i]>arr[j]){ var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr; } console.log(sort([7,5,2,4,3,9])) // your choice of data// alert(sort([7,5,2,4,3,9])) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM