Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

java - Sort elements of an array in ascending order

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 an assignment so I am not allowed to use existing sort methods. I'm supposed to write the method myself.

public class Sudoku {
    public static void main(String[] args) {
        int[] a = { 1, 4, 3, 5, 2 };
        System.out.println(Arrays.toString(sortArray(a)));
    }

    public static int[] sortArray(int[] nonSortedArray) {
        int[] sortedArray = new int[nonSortedArray.length];
        int temp;

        for (int i = 0; i < nonSortedArray.length - 1; i++) {
            if (nonSortedArray[i] > nonSortedArray[i + 1]) {
                temp = nonSortedArray[i];
                nonSortedArray[i] = nonSortedArray[i + 1];
                nonSortedArray[i + 1] = temp;
                sortedArray = nonSortedArray;
            }
        }

        return sortedArray;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
public static int[] sortArray(int[] nonSortedArray) {
        int[] sortedArray = new int[nonSortedArray.length];
        int temp;
        for (int j = 0; j < nonSortedArray.length - 1; j++) {// added this for loop, think about logic why do we have to add this to make it work

        for (int i = 0; i < nonSortedArray.length - 1; i++) {
            if (nonSortedArray[i] > nonSortedArray[i + 1]) {
                temp = nonSortedArray[i];
                nonSortedArray[i] = nonSortedArray[i + 1];
                nonSortedArray[i + 1] = temp;
                sortedArray = nonSortedArray;

            }
        }
        }
        return sortedArray;
    }

output:[1, 2, 3, 4, 5]

or

//making use of j

public static int[] sortArray(int[] nonSortedArray){
    int[] sortedArray = new int[nonSortedArray.length];
    int temp;
    for (int i = 0; i <= nonSortedArray.length; 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...