簡體   English   中英

使用不帶Array.sort的SelectionSort按字母順序對數組排序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM