0

I've been looking over Java arrays and tried to create my own SortArray() function rather than using somebody else's. If I pass the array [1, 2, 3, 4, 5] into the SortArray() function, it should return another array [5, 4, 3, 2, 1], sorting the array high to low. Instead, the function returns the exact same array as the array in the parameters. I commented what each code block should do in the code, please let me know if you find anything!

public static int[] sortArray(int[] array) {
    //Declare the highest value found so far
    int highest;

    //loop through every index in the array
    for (int minIndex = 0; minIndex < array.length; minIndex++) {

        //Set the current highest value to the first index
        highest = array[minIndex];

        //loop through every index past the minimum to check if there is a higher numer
        //do not check the indexes before the minIndex
        for (int i = 0 + minIndex; i < array.length; i++) {
            //Check to see if the current index is higher than the highest
            //if so, make that value the new highest and loop again from the next index
            if (array[i] > highest) {
                highest = array[i];
                minIndex ++;
            }
        }
    }
    return array;
}
2
  • simply, you're never updating the array. Commented Oct 9, 2017 at 18:45
  • Where are you ever changing the array? all you do is change the int highest and minIndex which is the for loop variable so you shouldn't even change that Commented Oct 9, 2017 at 18:45

1 Answer 1

1

You aren't mutating array at all. You aren't mutating elements in array at all either. You are just tracking what the highest is. Then highest goes away because the scope is gone.

Sign up to request clarification or add additional context in comments.

Comments

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.