Nick Gatti
Nick Gatti

Reputation: 73

Code isn't sorting right

So, I have my code, but my numbers aren't sorting. Is there something I'm missing?

My sort code, no other methods such as printing and such:

 public static int[] swapElement (int [] x, int index1, int index2) {
        int t = x[index1];
        x[index1] = x[index2];
        x[index2] = t; 
        return x;
    }
      public static int[] sortArray (int [] x) {
        int index = 0;
        int i=0;

        int[] toSort= new int[x.length];
       for(int m=0;m<x.length;m++){
        index = indexOfMaxInRange(x);
        toSort=swapElement(x,i,index);
        i++;
       }

      return toSort;
    }
      public static int indexOfMaxInRange (int[] x) {
        int max = 0;
        int i=0;
        int maxLocation = 0;
        while(i < x.length) {
            if (x[i] > max) {
                max = x[i];
                maxLocation= i;

            }
             i++;
        }       

Upvotes: 0

Views: 59

Answers (1)

kviiri
kviiri

Reputation: 3302

for(int m=0;m<x.length;m++){
    index = indexOfMaxInRange(x);
    toSort=swapElement(x,i,index);
    i++;
}

Here, you first place the maximum element to the first, then second, then third etc index. The problem is that instead of finding the second-greatest element to the second index, the third-greatest for the third and so on, you're just swapping around the greatest element.

To fix this, I suggest that you make your method indexOfMaxInRange live up to its name by specifying a range for it to search instead of having it look through the entire array.

EDIT: per request, here's how you add a lower bound to your method:

public static int indexOfMaxInRange (int[] x, int firstIndex) {
    int max = Integer.MIN_VALUE;
    int i=firstIndex; //note! initialize to min instead of 0
    int maxLocation = firstIndex;
    while(i < x.length) {
        if (x[i] > max) {
            max = x[i];
            maxLocation= i;

        }
        i++;
    }
    return maxLocation;
}

Notice the changes: the added argument (the first index to search - 0 would mean that the entire array is searched like before) and that i is initialized to this new argument.

(I also changed the initial value of max to Integer.MIN_VALUE to make it work even if the maximum value is negative but that shouldn't concern the original issue you had)

Upvotes: 1

Related Questions