2013-02-20 100 views
-2

我已经编写了下面的程序来对输入字符串进行排序,并输出按字典顺序排序的列表。尝试对字符串数组进行排序

似乎有问题,有人可以帮我找到它吗?

import java.util.ArrayList; 
import java.util.Scanner; 

public class Problem3 
{ 
    public static void main(String[] args) 
    { 
     Scanner scanner = new Scanner(System.in); 
     String statement = scanner.nextLine(); 
     screen(statement); 
    } 
    public static void screen(String statement) // sorting mechanism 
    { 
     String token[]= statement.split(" "); 
     String smallestSoFar=token[0]; 
     ArrayList<String> list = new ArrayList<String>(); 
     for(int i=0; i<token.length;i++) 
     { 
      smallestSoFar=token[i]; 
      for(int e=i; e<token.length; e++) 
      { 
       if(token[e].compareTo(smallestSoFar)<0) // inputting the // ...lexicographically sorted word into a new list 
       { 
        smallestSoFar=token[e]; 
        list.add(smallestSoFar);     
       } 
      } 
      System.out.println(list); 
     }   
    }  
} 

回答

1

的问题是,如果任何元件后面是更小的元素,也不会被打印出来(和较大的元件将被打印两次)。并且您的打印位置错误(应该在循环之后)。

您可以简单地使用

Arrays.sort(token) 

list = new ArrayList<String>(Arrays.asList(token)); 
Collections.sort(list); 

到数组排序。

如果你要坚持自己的方式,这里就是我会做它:

boolean[] checked = new boolean[token.length]; 
int checkedCount = 0; 
while (checkedCount < token.length) 
{ 
    int smallestIndex = -1; 
    for(int i = 0; i < token.length; i++) 
    { 
     if (!checked[i] && 
      (smallestIndex == -1 || token[i].compareTo(token[smallestIndex]) < 0)) 
     { 
      smallestIndex = i; 
     } 
    } 
    checked[smallestIndex] = true; 
    checkedCount++; 
    list.add(token[smallestIndex]); 
} 
System.out.println(list); 
相关问题