[英]How to sort array in alphabetical order without using Array.sort:Java
[英]Sort Array by Alphabetical order using SelectionSort without Array.sort
我將代碼引用到SelectionSorting上的mathebits網站,針對我的情況,將變量相應地從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;
}
}
該代碼不會給我錯誤。 但是,輸出未顯示它已按照字母順序排序。
您不能比較兩個String之類的數字,而是像String中那樣使用compareTo方法:
if (st[..].getLastName().compareTo(..) < 0) {..
同樣,要更改值,您需要在Student中使用新的Setter方法,例如:
public void setLastName(String name) {
this.name = name;
}
然后您可以這樣稱呼它:
st[..].setName(st[i].getName());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.