1

Ive written an array sort using the examples i found on this site. However my code isnt compiling right. Instead of storing the first value, it just stores the integer 0 and repeats it. I cant seem to find whats wrong with it, but i suspect it to be somewhere in my for loop.

/**
* @author angu2548
* XXX 310255325
*/
public class Sorter {

    public int[] sortArray(String[] args) {
        int [] numbers = new int [args.length];

        //Turning it into an int [] array
        for (int i= 0; i > args.length; i++){
            int x = Integer.parseInt(args[i]);
            numbers[i] = x;
        }

        //Insertion sort
        for(int j = 1; j < numbers.length; j++){
            int temp = numbers[j];
            int i = j -1;

            while (i  > 0 && numbers[i] > temp){
                numbers[i + 1] = numbers[i];
                i--;            
            }
            numbers[i + 1] = temp;
            //System.out.println("got to here");
        }
        return numbers;
    }       

    public static void main(String[] args) {        
        Sorter sort = new Sorter();
        int[] result = sort.sortArray(args); 
        if(result != null && result.length > 0){
            System.out.print("[" + result[0]);
            for(int i=1; i<result.length; ++i){
                System.out.print(", " + result[i]);
            }
            System.out.println("]");
        }
    }
}

The output is [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Even though my values are [1 2 3 4 5 6 7 8 8 5 4 3]

2 Answers 2

3

You made a mistake in the loop condition:

for (int i= 0; i > args.length; i++)

will prevent the loop from running, so numbers never gets initialized with the right elements. It should be

for (int i= 0; i < args.length; i++)
Sign up to request clarification or add additional context in comments.

Comments

2

Change '>' with '<' in the following line:

for (int i= 0; i > args.length; i++)

1 Comment

Opps, the same answer that @Peter Torok

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.