简体   繁体   English

使用不带Array.sort的SelectionSort按字母顺序对数组排序

[英]Sort Array by Alphabetical order using SelectionSort without Array.sort

I am referencing my code to mathebits website on SelectionSorting, changing the variables accordingly from int to String for my case, and adding in sort by alphabetical order as well. 我将代码引用到SelectionSorting上的mathebits网站,针对我的情况,将变量相应地从int更改为String ,并按字母顺序进行排序。

Below is my current code for SelectionSort of students by lastName : 下面是我当前的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;
        }
    }

The code does not give me error. 该代码不会给我错误。 However, the output does not show that it has been sorted according to alphabetical order. 但是,输出未显示它已按照字母顺序排序。

You cant compare two String like number, instead use compareTo method in String like: 您不能比较两个String之类的数字,而是像String中那样使用compareTo方法:

if (st[..].getLastName().compareTo(..) < 0) {..

Also to change value, you need to have new Setter method in Student like: 同样,要更改值,您需要在Student中使用新的Setter方法,例如:

public void setLastName(String name) {
    this.name = name;
} 

And then you could call it like: 然后您可以这样称呼它:

st[..].setName(st[i].getName());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM