具有相同起始字母的名称的排列

时间:2018-07-01 17:23:05

标签: java string

public class solution{
    public static void main(String [] args){
        String[] priya={"priya","nandhni","nithesh","varan","rekha","sri"};
        System.out.println(priya);
        int n=priya.length;
        for(int i=0,j=i+1;i<n;i++){
           if(priya[i].compareTo(priya[j])>0)
           {
               String temp=priya[i];
               priya[i]=priya[j];
               priya[j]=temp;
           }
        }
        for(int i=0;i<n;i++){
        System.out.println(priya[i]);
        }
    }
}

升序输出为

nandhni
varan
nithesh
priya
rekha
sri.

这里有什么错误?

2 个答案:

答案 0 :(得分:1)

排序逻辑是错误的,您只进行了一次元素比较

更正以下内容之一:

for (int i = 0; i < n; i++) { 
    for (int j = i + 1; j < n; j++) {
        if (priya[i].compareTo(priya[j]) > 0) {
            String temp = priya[i];
            priya[i] = priya[j];
            priya[j] = temp;
        }
    }
}

答案 1 :(得分:0)

尝试这个。嵌套循环,这样不仅可以比较相邻的元素,而且内部循环在最后一个元素处终止。

for (int i = 0; i < n-1; i++) {
    for (int j = i + 1; j < n; j++) {
        if (priya[i].compareTo(priya[j]) > 0) {
            String temp = priya[i];
            priya[i] = priya[j];
            priya[j] = temp;
        }
    }
}