Goodday! 我试图按年龄对数据(名称 - 年龄)进行排序。 我使用 QUICKSORT 算法,并且可以快速排序AGE,但如何使用各自的名称对Age进行排序?
我还搜索了Comparable和Comparator,但我不明白如何使用quicksort实现它。
这是我的quicksort代码。
import java.util.*;
import javax.persistence.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class OrderTester {
private static SessionFactory sessionFactory;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Session session = null;
Transaction transaction = null;
System.out.println("Press 1 to log in or press 2 to sign up");
int n = scan.nextInt();
if (n == 1) {
Customer c = new Customer();
// c.logIn();
} else if (n == 2) {
try {
sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Customer c = new Customer();
Address a = new Address();
session.save(c);
session.save(a);
Scanner read = new Scanner(System.in);
System.out.println("Enter a username");
String userName = read.next();
c.setUsername(userName);
System.out.println("Enter a password");
String password = read.next();
c.setPassword(password);
System.out.println("Enter the street name");
String streetName = read.next();
a.setStreetName(streetName);
System.out.println("Enter city");
String city = read.next();
a.setCity(city);
System.out.println("Enter state");
String state = read.next();
a.setState(state);
System.out.println("Enter zipcode");
String zipcode = read.next();
a.setZipCode(zipcode);
read.close();
transaction.commit();
} catch (Exception ex) {
transaction.rollback();
System.out.println("Transaction is rolled back.");
} finally {
session.close();
sessionFactory.close();
}
}
}
}
答案 0 :(得分:1)
要总结链接和注释,首先需要创建一个NameAndAge
类来封装这两个属性。那你有两个选择:
NameAndAge
Comparable<NameAndAge>
'自然'具有可比性
Comparator<NameAndAge>
并将其应用于列表。我认为(1)在这里是正确的选择。
以下示例远未完成(equals()
和hashCode()
应该被覆盖),但它演示了NameAndAge
的自然排序:名字优先(不区分大小写),然后是年龄(升序),它在使用Java现有的Collections.sort()
方法时起作用。
您需要为自己的算法做些什么:
int
=&gt;切换算法NameAndAge
,或理想情况Comparable<T>
current.compareTo(pivot)
。 Comparable
示例:
public static void main(String a[]){
List<NameAge> entries = new ArrayList<>();
entries.add( new NameAge("Zack", 2) );
entries.add( new NameAge("John", 37) );
entries.add( new NameAge("John", 11) );
entries.add( new NameAge("John", 5) );
entries.add( new NameAge("Andrew", 9) );
Collections.sort(entries);
for (NameAge each : entries) {
System.out.println(each.name + " (" + each.age + ")");
}
}
public static class NameAge implements Comparable<NameAge> {
String name;
int age;
public NameAge(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo( NameAge other) {
int nc = name.compareToIgnoreCase( other.name );
if (nc != 0) {
return nc;
}
return (age < other.age) ? -1 : ((age > other.age) ? 1 : 0);
}
}
产地:
Andrew (9)
John (5)
John (11)
John (37)
Zack (2)