views:

51

answers:

2

How do I do a bubble sort in java, The text file looks like this:

aaa

2

bbb

3

ccc

1

What I need to do is to loop through it and display the highest score to the lowest. When I run the code below, The numbers, are already sorted. and it will display 3, 2, then 1. But the name isn't in sync with the corresponding score, it will only display the names based on what's first. So the output will basically look like this, if I run the code below:

aaa  3

bbb  2

ccc  1

Function:

public void hi_score(){
    int i=0;
        try {
                 FileReader fr;
          fr = new FileReader (new File("F:\\pscores.txt"));
          BufferedReader br = new BufferedReader (fr);
          int ar=0;
          for(ar=0;ar<10;ar++){
          player_name[ar]=br.readLine();
          player_score[ar]=Integer.parseInt(br.readLine());
          }

            } catch (Exception e) { e.printStackTrace();}

              bubble_srt(player_score, player_score.length);
        System.out.print("Highscores:\n");
        System.out.println("Scores");

        System.out.println("Name\tScore");
        for(i = 0; i <NUMBER_OF_HI_SCORE; i++){
          System.out.print(player_name[i] + "\t" +player_score[i] + "\n");

        }
    }

How do I do this, without using arraylist. Just ordinary array.

+2  A: 

This is because you are sorting only the player_score array:

bubble_srt(player_score, player_score.length);

You also need to send the player_name array to the function, sort as you were sorting before(based on score) and every time you swap two scores, you'll have to swap the names as well.

codaddict
+2  A: 

Should create a single array that combines the player and the respective score as an String[]; create a single array of scores that gets bubble sorted

then as you have an sorted int[] player_score array, you can try to match it up via substring of the elements in String[] playername + score

edit: so after the bubble sort, when you are going to print it, perhaps take the newly sorted array of scores, try to match with an appropriate element of the array of String[] playername + score, then print out the element that matches the 0th, 1st, 2nd values of the sorted score array.

Kevin Zhou