1

I have a class where I have to make a program that reads in a bunch of data puts it into several different arrays. I then have to sort them but my method seems to not be working.

inside of my first for loop I have the two if statements for the two situations I would need to address. The first situation would be if the the team name comes before and the second is when the team name is the same. If the team name is the same it sorts by yards.

The name sorting works fine but when I un-comment the second statement it sorts it a order I can't figure out.

public static void sortDatabase(int numRecords, String[] teamArr,
        int[] attemptsArr, int[] yardsArr, int[] winsArr,
        int[] loseArr)
{

    //Sort the database first according to name and then according to yards
    System.out.println("Sort the database.\n");

    int iMin;

    String teamTemp;
    int attemptTemp;
    int yardTemp;
    int winsTemp;
    int loseTemp;

    for(int i = 0; i < numRecords - 1; i++)
    {
        iMin = i;

        for(int k = i + 1; k < numRecords; k++)
        {
            int compare = teamArr[k].compareTo(teamArr[iMin]);
            if(compare < 0)
            {
                iMin = k;
            }
            else if(compare == 0 && yardsArr[k] < yardsArr[iMin])
            {                
                iMin = k;
            }

            //swap out all data
            teamTemp = teamArr[i];
            attemptTemp = attemptsArr[i];
            yardTemp = yardsArr[i];
            winsTemp = winsArr[i];
            loseTemp = loseArr[i];

            teamArr[i] = teamArr[iMin];
            attemptsArr[i] = attemptsArr[iMin];
            yardsArr[i] = yardsArr[iMin];
            winsArr[i] = winsArr[iMin];
            loseArr[i] = loseArr[iMin];

            teamArr[iMin] = teamTemp;
            attemptsArr[iMin] = attemptTemp;
            yardsArr[iMin] = yardTemp;
            winsArr[iMin] = winsTemp;
            loseArr[iMin] = loseTemp;
        }
    }
}

Also don't comment or answer with better ways to do this or say that I should make a new class to handle all the data. Just try and answer with the sort method I am using. I am doing this for a class and have little options.

1 Answer 1

1

The bit that's labeled //swap out all data needs to come after the for-loop that sets iMin, rather than inside it. Right now you're doing swaps in the middle of setting iMin, and that will cause iMin to become wrong and the wrong elements to be swapped.

1
  • I can't believe that was it. I was so focused on the if statements. Thank you.
    – Brandon
    Nov 19, 2011 at 22:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.