简体   繁体   English

如何在Java中对文本文件进行冒泡排序

[英]How to bubble sort through a text file in Java

How do I do a bubble sort in java, The text file looks like this: 如何在Java中进行气泡排序,文本文件如下所示:

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. 它将显示3、2,然后是1。但是名称与对应的乐谱并不同步,它只会根据名字顺序显示名称。 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. 我如何做到这一点,而不使用arraylist。 Just ordinary array. 只是普通的数组。

This is because you are sorting only the player_score array: 这是因为您仅对player_score数组进行排序:

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. 您还需要将player_name数组发送到函数,按之前的排序进行排序(基于分数),并且每次交换两个分数时,也必须交换名称。

Should create a single array that combines the player and the respective score as an String[]; 应该创建一个将玩家和各自得分组合为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 那么当您拥有一个已排序的int [] player_score数组时,您可以尝试通过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. 编辑:因此,在冒泡排序之后,当您要打印它时,也许采用新排序的分数数组,尝试与String [] playername + score数组的适当元素匹配,然后打印出与之匹配的元素排序分数数组的第0,第1,第2个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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