简体   繁体   中英

Trouble sorting parallel arrays

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM