排序为什么我的气泡排序不起作用?JAVA
第一次发帖! 我有一个作业要交,要求我写一个java程序,从文本文件中读取数据,并根据分数和首字母对其进行排序。 文本文件如下:
John Doe 75
Joe Blow 65
Mary Smith 80
John Green 82
Jill White 97
这是我的代码:
import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) throws Exception{
String[] firstName = new String[5];
String[] lastName = new String[5];
int score[] = new int[5];
java.io.File file = new java.io.File("data.txt");
Scanner input = new Scanner(file);
int c=0;
while(input.hasNext()){
firstName[c] = input.next();
lastName[c] = input.next();
score[c] = input.nextInt();
c++;
}
input.close();
MichaelBubbleSort(score);
for(int x=4;x>=0;x--){
System.out.print(firstName[x].substring(0,1) + lastName[x].substring(0,1) + " " + score[x]);
System.out.println();
}
}
public static void MichaelBubbleSort(int[] arr){
int temp;
for(int i=0; i < arr.length-1; i++){
for(int j=1; j < arr.length-i; j++){
if(arr[j-1] > arr[j]){
temp=arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
}
但出于某种原因,它总是这样:
JW 97
JG 82
MS 80
JB 75
JD 65
输出应为:
JW 97
JG 82
MS 80
JD 75
JB 65
为什么这种情况一直发生
# 1 楼答案
这是符合您的代码的解决方案。但代码必须比这个更好。你应该使用集合类。 在这段代码中,您需要相应地交换名称
# 2 楼答案
之所以会这样,是因为你没有根据分数对名字进行排序。我建议使用对象数组存储数据,然后使用冒泡排序对对象数组进行排序,如下所示:
对象类来保存数据