gpt4 book ai didi

java - 通过合并排序对对象属性进行排序

转载 作者:行者123 更新时间:2023-12-02 11:51:42 26 4
gpt4 key购买 nike

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

我的 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;
}
}

我见过人们使用比较器对对象属性的 ArrayList 进行排序。但是,他们使用它进行内置排序,如下行(很简单):

Collections.sort(Database.arrayList, new CustomComparator());

但是,我想使用我在 Student 类中编写的合并排序函数。但我仍然不明白如何将属性“rollNum”传递到 mergesort 函数中,以及 ArrayList 中的其他属性将如何相应移动?我在 Google 中从未见过这种情况。

这是我的完整代码:

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();
}
}

最佳答案

您的 Student 已经可比较,并且它已经与使用 rollNum< 的其他 Student 实例进行比较 字段,因此当前使用 compareTo() 的实现应该已经在该字段上排序。

但是如果您想使用不同的顺序进行排序,您可以编写一个 Comparator 并更改排序方法,如下所示:

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)
}

在这里,您不需要使用 Comparable 来限制 T

关于java - 通过合并排序对对象属性进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47838602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com