How do I properly bubble sort through a text file by assigning the values to an array.
In the code below I tried to assign the values from the text file to a string while there is still something to fetch. Then I used a for loop to assign the one that I have fetch to the array.
Then tried to use the bubble sort to hopefully sort the numbers that I have fetch from highest to lowest. But I get this one as an output:
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78
12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12
29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29
Here’s my code:
try{
int i;
String ss;
FileReader fr;
fr = new FileReader (new File("X:\\file.txt"));
BufferedReader br = new BufferedReader (fr);
while ((ss = br.readLine()) != null) {
String[] sv = ss.split(" ");
String splayer_name=sv[1];
String s_player_score=sv[2];
for(int xy=0;xy<player_name.length;xy++){
player_name[xy]=splayer_name;
player_score[xy]=Integer.parseInt(s_player_score);
}
bubble_srt(player_score, player_score.length);
for(i = 0; i <player_score.length; i++)
System.out.print(player_score[i]+" ");
System.out.println();
}
}catch(Exception e){}
Please help,
update:
someone asked about the file structure, are you referring to this one:
This is the file.txt, the one that I’m fetching is the rightmost number:
1 a 5
2 b 10
5 x 4
7 h 20
bubble_srt()call outside the while loop. You are replacing the entire contents on each iteration like what the earlier answer has correctly pointed out. You only want to sort AFTER the entire file contents are read.Since your file can be of any size there is no way to initialize the array beforehand unless you want to perform two reads one to get the count and then to read into the array. You would be better off using a List. Here’s a skeleton code:
(Modify your bubble sort to take a list input)