簡體   English   中英

Java數組排序不起作用

[英]Java array sorting not work

我是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;
}

謝謝你的幫助

像下面這樣修改您的方法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; 
}

您可以嘗試以下代碼。我解釋了代碼如何與注釋一起使用:

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;
            }
        }
    }

}

在這里,您可以以更簡單的合成方式對它進行排序。 如果您喜歡javascript。 看看這個。

 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