Sort elements of an array in ascending order

后端 未结 5 1898
陌清茗
陌清茗 2020-12-18 12:26

I\'m trying to sort an array in ascending order. For some reason it only performs the for loop once. Why doesn\'t it keep going until everything is sorted?

It\'s for

5条回答
  •  不知归路
    2020-12-18 13:21

    You are trying to sort an array using a single loop. You would be needing two loops to ensure that the elements are in sorted order.

    public static int[] sortArray(int[] nonSortedArray) 
    {
        int[] sortedArray = new int[nonSortedArray.length];
        int temp;
        for (int i = 0; i < nonSortedArray.length-1; i++) 
        {
            for (int j = i+1; j < nonSortedArray.length; j++)
            {
                if (nonSortedArray[i] > nonSortedArray[j]) 
                {
                    temp = nonSortedArray[i];
                    nonSortedArray[i] = nonSortedArray[j];
                    nonSortedArray[j] = temp;
                    sortedArray = nonSortedArray;
                }
            }
        }
        return sortedArray;
    }
    

提交回复
热议问题