Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 按合并排序对对象属性进行排序_Java_Sorting_Arraylist - Fatal编程技术网

Java 按合并排序对对象属性进行排序

Java 按合并排序对对象属性进行排序,java,sorting,arraylist,Java,Sorting,Arraylist,我想根据学生的卷号对他们进行分类。我知道如何使用合并排序对整数数组列表进行排序,但对Student类型的数组列表进行排序是不同的 my Student类包含以下属性: public static class Student { String name; int rollNum, WebMark, dsMark, dmMark; public Student(String name, int rollNum, int WebMark, in

我想根据学生的卷号对他们进行分类。我知道如何使用合并排序对整数数组列表进行排序,但对Student类型的数组列表进行排序是不同的

my Student类包含以下属性:

public static class Student
    {
        String name;
        int rollNum, WebMark, dsMark, dmMark;

        public Student(String name, int rollNum, int WebMark, int dsMark, int dmMark)
        {
            this.name = name;
            this.rollNum = rollNum;
            this.WebMark = WebMark;
            this.dsMark = dsMark;
            this.dmMark = dmMark;
        }
}
我见过人们使用比较器对对象属性的数组列表进行排序。但是,他们使用它进行内置排序,如下面的一行(很简单):

但是,我想使用我在学生课堂上编写的mergesort函数。但我仍然不明白如何将属性“rollNum”传递到mergesort函数中,以及如何相应地移动ArrayList中的其他属性?我在谷歌的任何地方都没见过这个

这是我的全部代码:

package student;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Comparator;

public class Main 
{
    public static class Student
    {
        String name;
        int rollNum, WebMark, dsMark, dmMark;

        public Student(String name, int rollNum, int WebMark, int dsMark, int dmMark)
        {
            this.name = name;
            this.rollNum = rollNum;
            this.WebMark = WebMark;
            this.dsMark = dsMark;
            this.dmMark = dmMark;
        }
        public String getName()
        {
            return name;
        }
        public int getRollNum()
        {
            return rollNum;
        }
        public int getWebMark()
        {
            return WebMark;
        }
        public int getDSMark()
        {
            return dsMark;
        }
        public int getDMMark()
        {
            return dmMark;
        }
        public static void addStudent(ArrayList<Student> studentArray)
        {
            Scanner input = new Scanner(System.in);
            System.out.println("Enter Name: ");
            String name = input.next();
            System.out.println("Enter Roll Number");
            int rollNum = input.nextInt();
            System.out.println("Enter Web Mark:");
            int webMark = input.nextInt();
            System.out.println("Enter Data Structure Mark:");
            int DSMark = input.nextInt();
            System.out.println("Enter Discrete Math Mark:");
            int DMMark = input.nextInt();
            //create this student profile in array 
            Student newStudent = new Student(name,rollNum,webMark,DSMark,DMMark);
            studentArray.add(newStudent);
        }
        public static void findStudent(int rollNum, ArrayList<Student> studentArr)
        {
            for(int i = 0; i < studentArr.size(); i++)
            {
                if(studentArr.get(i).getRollNum()==rollNum)
                {
                    System.out.println("Roll Number: " + studentArr.get(i).getRollNum() +
                                        ", Name: " + studentArr.get(i).getName() +
                                        ", Web Grade: " + studentArr.get(i).getWebMark() +
                                        ", Data Structure Grade: " + studentArr.get(i).getDSMark() +
                                        ", Discrete Math Grade: " + studentArr.get(i).getDMMark());
                }
                else
                {
                    System.out.println("Couldn't find student.");
                }
            }
        }
        public static void deleteStudent(ArrayList<Student> studentArr)
        {
            System.out.println("Enter Student Roll Number: ");
            Scanner input = new Scanner(System.in);
            int rollNum = input.nextInt();
            for(int counter = 0; counter < studentArr.size(); counter++)
            {
                if(studentArr.get(counter).getRollNum() == rollNum)
                {
                    studentArr.remove(counter);
                }
            }
        }

        public String toString()
        {
            return name + " " + rollNum + " " + WebMark + " " + dsMark + " " + dmMark;
        }

        public static double avg(ArrayList<Student> studentArr)
        {
            double[] avgArr = new double[studentArr.size()];
            double max = 0.0;
            for(int counter = 0; counter < studentArr.size(); counter++)
            {
                avgArr[counter] = (studentArr.get(counter).getWebMark() + 
                        studentArr.get(counter).getDSMark() + studentArr.get(counter).getDMMark())/(3);

                if(avgArr[counter] > max)
                {
                    max = avgArr[counter];
                }
            }
            return max;
        }

        public int compareTo(Student studCompare)
        {
            int compareRollNum = ((Student) studCompare).getRollNum();

            //ascending order
            return this.rollNum - compareRollNum;
        }

        /*Comparator for sorting the array by student name*/
        public static Comparator<Student> StuNameComparator = new Comparator<Student>() 
        {
            public int compare(Student s1, Student s2) 
            {
               String StudentName1 = s1.getName().toUpperCase();
               String StudentName2 = s2.getName().toUpperCase();

               //ascending order
               return StudentName1.compareTo(StudentName2);

               //descending order
               //return StudentName2.compareTo(StudentName1);
            }
        };

        /*Comparator for sorting the array by student name*/
        public static Comparator<Student> StuRollno = new Comparator<Student>() 
        {
            public int compare(Student s1, Student s2) 
            {
                int rollno1 = s1.getRollNum();
                int rollno2 = s2.getRollNum();

               //ascending order
                return rollno1-rollno2;

               //descending order
               //return StudentName2.compareTo(StudentName1);
            }
        };

        public static <T extends Comparable<T>> List<T> mergeSort(List<T> m)
        {
            // exception
            if (m==null) throw new NoSuchElementException("List is null");
            // base case
            if (m.size() <= 1) return m;

            // make lists
            List<T> left = new ArrayList<>();
            List<T> right = new ArrayList<>();

            // get middle
            int middle = m.size()/2;

            // fill left list
            for (int i = 0; i < middle; i++)
            {
                if (m.get(i)!=null) left.add(m.get(i));
            }

            // fill right list
            for (int i = middle; i < m.size(); i++)
            {
                if (m.get(i)!=null) right.add(m.get(i));
            }

            // recurse
            left = mergeSort(left);
            right = mergeSort(right);

            // merge
            return merge(left,right);
        }

        private static <T extends Comparable<T>> List<T> merge(List<T> left, List<T> right)
        {
            List<T> result = new ArrayList<>();

            // merge
            while (!left.isEmpty() && !right.isEmpty())
            {
                if (left.get(0).compareTo(right.get(0)) <= 0)
                {
                    result.add(left.remove(0));
                }
                else
                {
                    result.add(right.remove(0));
                }
            }

            // cleanup leftovers
            while (!left.isEmpty())
            {
                result.add(left.remove(0));
            }
            while (!right.isEmpty())
            {
                result.add(right.remove(0));
            }
            return result;
        }

    }

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int userChoice = 0;
        int userChoice2 = 0;
        ArrayList<Student> studentArr = new ArrayList<Student>(); //array size is 6

        System.out.println("1- Merge Sort");
        System.out.println("2- Shell Sort");
        System.out.println("3- Quit");
        userChoice2 = input.nextInt();

        if (userChoice2 == 1 || userChoice2 == 2) 
        {
            do {
                System.out.println("1- Add a New Record");
                System.out.println("2- Sort by Student Name");
                System.out.println("3- Sort by Roll Number");
                System.out.println("4- Delete a Student Specific Record");
                System.out.println("5- Display a Student Specific Record");
                System.out.println("6- Search");
                System.out.println("7- Display the Highest Average");
                System.out.println("8- Print"); //print the array size, sort time, and number of comparisons to the screen.
                System.out.println("9- Quit");
                System.out.println("Select your Option: \n");

                userChoice = input.nextInt();

                switch (userChoice) {
                case 1:
                    Student.addStudent(studentArr);
                    break;
                case 2:
                    if (userChoice2 == 1) {
                        //call mergesort function
                    } else if (userChoice2 == 2) {
                        //call shell sort function
                    }
                case 3:
                    if (userChoice2 == 1) {
                        //call mergesort function
                    } else if (userChoice2 == 2) {
                        //call shell sort function
                    }
                case 4:
                    Student.deleteStudent(studentArr);
                    break;
                case 5:
                    System.out.println("Enter Student Roll Number: ");
                    int rollNum_ = input.nextInt();
                    Student.findStudent(rollNum_, studentArr);
                    break;
                case 6:
                case 7:
                    double highestAvg = Student.avg(studentArr);
                    System.out.println("Highest Average is: " + highestAvg);
                    break;
                case 8:
                    System.out.println("Printing students...");
                    System.out.print(studentArr);
                    System.out.println("\n");
                    break;
                case 9:
                }
            } while (userChoice != 9);
        }
        else
        {
            return;
        }
        input.close();
    }
}
package学生;
导入java.util.List;
导入java.util.NoSuchElementException;
导入java.util.ArrayList;
导入java.util.Scanner;
导入java.util.Comparator;
公共班机
{
公立静态班学生
{
字符串名;
int rollNum、WebMark、dsMark、dmMark;
公立学生(字符串名、int rollNum、int WebMark、int dsMark、int dmMark)
{
this.name=名称;
this.rollNum=rollNum;
this.WebMark=WebMark;
this.dsMark=dsMark;
this.dmMark=dmMark;
}
公共字符串getName()
{
返回名称;
}
public int getRollNum()
{
返回rollNum;
}
public int getWebMark()
{
返回WebMark;
}
public int getDSMark()
{
返回dsMark;
}
public int getDMMark()
{
返回dmMark;
}
公共静态void addStudent(ArrayList studentArray)
{
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入名称:”);
String name=input.next();
System.out.println(“输入卷号”);
int rollNum=input.nextInt();
System.out.println(“输入Web标记:”);
int webMark=input.nextInt();
System.out.println(“输入数据结构标记:”);
int DSMark=input.nextInt();
System.out.println(“输入离散数学标记:”);
int-DMMark=input.nextInt();
//在数组中创建此学生配置文件
学生新闻学生=新学生(姓名、rollNum、网络标记、DSMark、DMMark);
studentArray.add(newStudent);
}
公共静态void findStudent(int rollNum,ArrayList studentar)
{
对于(int i=0;i最大值)
{
max=avgArr[计数器];
}
}
返回最大值;
}
公共int比较(学生比较)
{
int compareRollNum=((学生)studCompare.getRollNum();
//升序
返回this.rollNum-compareRollNum;
}
/*用于按学生姓名对数组进行排序的比较器*/
公共静态比较器=新比较器()
{
公共整数比较(学生s1、学生s2)
{
字符串StudentName1=s1.getName().toUpperCase();
字符串StudentName2=s2.getName().toUpperCase();
//升序
返回StudentName1.compareTo(StudentName2);
//降序
//返回StudentName2.compareTo(StudentName1);
}
};
/*用于按学生姓名对数组进行排序的比较器*/
公共静态比较器StuRollno=新比较器()
{
公共整数比较(学生s1、学生s2)
{
int rollno1=s1.getRollNum();
int rollno2=s2.getRollNum();
//升序
返回辊1-2;
//降序
//返回StudentName2.compareTo(StudentName1);
}
};
公共静态列表合并排序(列表m)
{
//例外情况
如果(
package student;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Comparator;

public class Main 
{
    public static class Student
    {
        String name;
        int rollNum, WebMark, dsMark, dmMark;

        public Student(String name, int rollNum, int WebMark, int dsMark, int dmMark)
        {
            this.name = name;
            this.rollNum = rollNum;
            this.WebMark = WebMark;
            this.dsMark = dsMark;
            this.dmMark = dmMark;
        }
        public String getName()
        {
            return name;
        }
        public int getRollNum()
        {
            return rollNum;
        }
        public int getWebMark()
        {
            return WebMark;
        }
        public int getDSMark()
        {
            return dsMark;
        }
        public int getDMMark()
        {
            return dmMark;
        }
        public static void addStudent(ArrayList<Student> studentArray)
        {
            Scanner input = new Scanner(System.in);
            System.out.println("Enter Name: ");
            String name = input.next();
            System.out.println("Enter Roll Number");
            int rollNum = input.nextInt();
            System.out.println("Enter Web Mark:");
            int webMark = input.nextInt();
            System.out.println("Enter Data Structure Mark:");
            int DSMark = input.nextInt();
            System.out.println("Enter Discrete Math Mark:");
            int DMMark = input.nextInt();
            //create this student profile in array 
            Student newStudent = new Student(name,rollNum,webMark,DSMark,DMMark);
            studentArray.add(newStudent);
        }
        public static void findStudent(int rollNum, ArrayList<Student> studentArr)
        {
            for(int i = 0; i < studentArr.size(); i++)
            {
                if(studentArr.get(i).getRollNum()==rollNum)
                {
                    System.out.println("Roll Number: " + studentArr.get(i).getRollNum() +
                                        ", Name: " + studentArr.get(i).getName() +
                                        ", Web Grade: " + studentArr.get(i).getWebMark() +
                                        ", Data Structure Grade: " + studentArr.get(i).getDSMark() +
                                        ", Discrete Math Grade: " + studentArr.get(i).getDMMark());
                }
                else
                {
                    System.out.println("Couldn't find student.");
                }
            }
        }
        public static void deleteStudent(ArrayList<Student> studentArr)
        {
            System.out.println("Enter Student Roll Number: ");
            Scanner input = new Scanner(System.in);
            int rollNum = input.nextInt();
            for(int counter = 0; counter < studentArr.size(); counter++)
            {
                if(studentArr.get(counter).getRollNum() == rollNum)
                {
                    studentArr.remove(counter);
                }
            }
        }

        public String toString()
        {
            return name + " " + rollNum + " " + WebMark + " " + dsMark + " " + dmMark;
        }

        public static double avg(ArrayList<Student> studentArr)
        {
            double[] avgArr = new double[studentArr.size()];
            double max = 0.0;
            for(int counter = 0; counter < studentArr.size(); counter++)
            {
                avgArr[counter] = (studentArr.get(counter).getWebMark() + 
                        studentArr.get(counter).getDSMark() + studentArr.get(counter).getDMMark())/(3);

                if(avgArr[counter] > max)
                {
                    max = avgArr[counter];
                }
            }
            return max;
        }

        public int compareTo(Student studCompare)
        {
            int compareRollNum = ((Student) studCompare).getRollNum();

            //ascending order
            return this.rollNum - compareRollNum;
        }

        /*Comparator for sorting the array by student name*/
        public static Comparator<Student> StuNameComparator = new Comparator<Student>() 
        {
            public int compare(Student s1, Student s2) 
            {
               String StudentName1 = s1.getName().toUpperCase();
               String StudentName2 = s2.getName().toUpperCase();

               //ascending order
               return StudentName1.compareTo(StudentName2);

               //descending order
               //return StudentName2.compareTo(StudentName1);
            }
        };

        /*Comparator for sorting the array by student name*/
        public static Comparator<Student> StuRollno = new Comparator<Student>() 
        {
            public int compare(Student s1, Student s2) 
            {
                int rollno1 = s1.getRollNum();
                int rollno2 = s2.getRollNum();

               //ascending order
                return rollno1-rollno2;

               //descending order
               //return StudentName2.compareTo(StudentName1);
            }
        };

        public static <T extends Comparable<T>> List<T> mergeSort(List<T> m)
        {
            // exception
            if (m==null) throw new NoSuchElementException("List is null");
            // base case
            if (m.size() <= 1) return m;

            // make lists
            List<T> left = new ArrayList<>();
            List<T> right = new ArrayList<>();

            // get middle
            int middle = m.size()/2;

            // fill left list
            for (int i = 0; i < middle; i++)
            {
                if (m.get(i)!=null) left.add(m.get(i));
            }

            // fill right list
            for (int i = middle; i < m.size(); i++)
            {
                if (m.get(i)!=null) right.add(m.get(i));
            }

            // recurse
            left = mergeSort(left);
            right = mergeSort(right);

            // merge
            return merge(left,right);
        }

        private static <T extends Comparable<T>> List<T> merge(List<T> left, List<T> right)
        {
            List<T> result = new ArrayList<>();

            // merge
            while (!left.isEmpty() && !right.isEmpty())
            {
                if (left.get(0).compareTo(right.get(0)) <= 0)
                {
                    result.add(left.remove(0));
                }
                else
                {
                    result.add(right.remove(0));
                }
            }

            // cleanup leftovers
            while (!left.isEmpty())
            {
                result.add(left.remove(0));
            }
            while (!right.isEmpty())
            {
                result.add(right.remove(0));
            }
            return result;
        }

    }

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int userChoice = 0;
        int userChoice2 = 0;
        ArrayList<Student> studentArr = new ArrayList<Student>(); //array size is 6

        System.out.println("1- Merge Sort");
        System.out.println("2- Shell Sort");
        System.out.println("3- Quit");
        userChoice2 = input.nextInt();

        if (userChoice2 == 1 || userChoice2 == 2) 
        {
            do {
                System.out.println("1- Add a New Record");
                System.out.println("2- Sort by Student Name");
                System.out.println("3- Sort by Roll Number");
                System.out.println("4- Delete a Student Specific Record");
                System.out.println("5- Display a Student Specific Record");
                System.out.println("6- Search");
                System.out.println("7- Display the Highest Average");
                System.out.println("8- Print"); //print the array size, sort time, and number of comparisons to the screen.
                System.out.println("9- Quit");
                System.out.println("Select your Option: \n");

                userChoice = input.nextInt();

                switch (userChoice) {
                case 1:
                    Student.addStudent(studentArr);
                    break;
                case 2:
                    if (userChoice2 == 1) {
                        //call mergesort function
                    } else if (userChoice2 == 2) {
                        //call shell sort function
                    }
                case 3:
                    if (userChoice2 == 1) {
                        //call mergesort function
                    } else if (userChoice2 == 2) {
                        //call shell sort function
                    }
                case 4:
                    Student.deleteStudent(studentArr);
                    break;
                case 5:
                    System.out.println("Enter Student Roll Number: ");
                    int rollNum_ = input.nextInt();
                    Student.findStudent(rollNum_, studentArr);
                    break;
                case 6:
                case 7:
                    double highestAvg = Student.avg(studentArr);
                    System.out.println("Highest Average is: " + highestAvg);
                    break;
                case 8:
                    System.out.println("Printing students...");
                    System.out.print(studentArr);
                    System.out.println("\n");
                    break;
                case 9:
                }
            } while (userChoice != 9);
        }
        else
        {
            return;
        }
        input.close();
    }
}
private static <T> List<T> merge(List<T> left, List<T> right, Comparator<? super T> comparator) {
    .. use comparator.compare(a, b) instead of a.compareTo(b)
}