我将我的代码引用到 Mathebits 网站上的 SelectionSorting,根据我的情况将变量相应地从 int
更改为 String
,并按字母顺序添加排序。
下面是我当前按lastName
对学生进行SelectionSort
的代码:
public static void SelectionSort(Student[] st) {
int i, j, first;
String temp;
String jLastName = "";
String firstLastName = "";
String iLastName ="";
for (i = st.length - 1; i > 0; i--) {
first = 0;
for (j = 1; j <= i; j++)
{
if (st[j].getLastName() != null) {
jLastName=st[j].getLastName();
if (st[first].getLastName() != null) {
firstLastName = st[first].getLastName();
if ((jLastName.compareToIgnoreCase(firstLastName)) > 0) {
first = j;
}
}
}
}
iLastName = st[i].getLastName();
temp = firstLastName;
firstLastName = iLastName;
iLastName = temp;
}
}
代码没有给我错误。但是,输出并未显示它已按字母顺序排序。
最佳答案
你不能比较两个像数字这样的字符串,而是在字符串中使用compareTo方法,例如:
if (st[..].getLastName().compareTo(..) < 0) {..
还要更改值,您需要在 Student 中使用新的 Setter 方法,例如:
public void setLastName(String name) {
this.name = name;
}
然后你可以这样调用它:
st[..].setName(st[i].getName());
关于java - 使用选择排序(不使用 Array.sort)按字母顺序对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29102702/