对数组中两个最高的数字进行排序

时间:2012-03-19 20:26:33

标签: java

我很遗憾地问,但是我在书中练习时遇到了麻烦,我不确定如何修复它。输入学生的姓名和分数后,我会找到最高和第二高分。但是我找不到找到两个最高分的正确方法。

我使用的当前方式有效,但用户无法输入从低到高的分数,例如70,80和90.如果完成90,80和70,它会对数字进行适当的排序。

有什么我可以改变/做/读的让我走上正确的道路吗?

import java.util.Scanner;

public class StudentSort {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // For finding highest scores with corresponding array
        double firstHighest = 0;
        int firstEntry = 0;
        double secondHighest = 0;
        int secondEntry = 0;

        System.out.print("Enter the number of students: ");
        int studentCount = input.nextInt();

        // Length of arrays set
        int[] studentScores = new int[studentCount];
        String[] studentName = new String[studentCount];

        // Go through loop to set scores and names of each student
        for (int i = 0; i < studentCount; i++) {
            System.out.print("Enter a student name: ");
            studentName[i] = input.next();
            System.out.print("Enter a student score: ");
            studentScores[i] = input.nextInt();
            }

        // Find out the highest and second highest scores
        // Problem with secondHighest/Entry
        for (int i = 0; i < studentScores.length; i++) {
            if (studentScores[i] > firstHighest) {
                secondHighest = firstHighest;
                firstHighest = studentScores[i];
                firstEntry = i;
        } else if (studentScores[i] > secondHighest) {
                secondHighest = studentScores[i];
                secondEntry = i;
        }
    }

    System.out.println("Top two students: ");
    System.out.println(studentName[firstEntry] + "'s score is " + firstHighest);
    System.out.println(studentName[secondEntry] + "'s score is " + secondHighest);
    }
}

与往常一样,我感谢您提供的任何帮助。

5 个答案:

答案 0 :(得分:5)

当您获得新的最高分时,您似乎忘了更新secondEntry。行前:

            firstEntry = i;

尝试添加:

            secondEntry = firstEntry;

答案 1 :(得分:4)

问题出在这里

    if (studentScores[i] > firstHighest) {
        secondHighest = firstHighest;
        firstHighest = studentScores[i];
        firstEntry = i;
    }

您成功更新了secondHighest和firstHighest的值,但是您没有修复secondEntry;

你需要添加

secondEntry = firstEntry;

firstEntry = i;

答案 2 :(得分:1)

有多种方法可以解决这个问题。最直观的方法就是拿起一手牌(即插入排序)。将输入视为连续的卡片列表。它们进入的顺序并不重要,因为大多数玩家会将它们从最低到最高(或者相反)进行排序。

所以在你的输入循环中:

 while(...some_condition_that_ensures_more_input){
     //this can be a list for instance, which you keep in order
     list =  insert_into_correct_place(input);                                             
 }

 /**
   Assuming 
   a)you sort from lowest to highest 
   b)there is more than 1 input entered):
 */
 highest = list.get(list.length()-1)
 second_highest = list.get(list.length()-2)

另一种直观的方式(实际上更快)是跟踪两个变量:

 int [] highest = {Integer.MIN_VALUE(), Integer.MIN_VALUE()};      
 while(...){
      highest = replace_lowest(input, highest);
 }

 /**
  * arr is sorted from lowest to highest : arr[0] is always <= arr[1] 
  */
 int [] replace_lowest(int input, int [] arr){          
     //Case 0 : input is less than both the highest 2 numbers
     //         or is equal to one of them
     if (input < arr[0] || input == arr[0] || input == arr[1]) { return arr; }

     //Case 1 : input is greater than one of the highest 2, but not both
     if (input > arr[0] && input < arr[1]) { arr[0] = input; return arr; }

     //Case 2 : input is greater than both of the highest 2 numbers
     second_highest = arr[1]; arr[0] = arr[1]; arr[1] = input;
     return arr;      
 }

第一种方法更灵活一些(它可以让你选出X最高的数字,而不只是两个)。如果你知道你将永远不必重新调整输出变量的数量,第二种方法会更快。

答案 3 :(得分:0)

您只需使用java.util.Arrays类及其sort()方法即可。这是代码的样子:

Arrays.sort(studentScores);
int firstHighest = studentScores[studentScores.length - 1];
int secondHighest = studentScores[studentScores.length - 2];

希望这有帮助。

答案 4 :(得分:0)

我在内部阶级的帮助下给你写了一个方法;它返回一个数组,第一个元素是得分最高的学生,第二个学生是第二个得分的学生。

import java.util.Arrays;
import java.util.Comparator;

public class StudentSort {

static class Student {
        Student(int score, String name) {
        this.score = score;
        this.name = name;
        }
        int score;
        String name;
    }

    private static Student[] test(int[] studentScores, String[] studentNames) {
        Student[] students = new Student[studentScores.length];
        for(int i = 0; i < studentScores.length; i++) {
        students[i] = new Student(studentScores[i], studentNames[i]);
        }
        Arrays.sort(students, new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            return new Integer(o1.score).compareTo(o2.score);
        }
    });
        return new Student[]{students[0], students[1]};
    }

    public static void main(String[] args) {
        int[] studentScores = new int[] {5, 9, 7};
        String[] studentNames = new String[]{"Jan", "Bert", "Piet"};
        Student[] students = test(studentScores, studentNames);
        System.out.println("heighest: " + students[0].name + ": " + students[0].score);
        System.out.println("second: " + students[1].name + ": " + students[1].score);
    }
}