如何对单词进行排序"你好"在java中使用递归?

时间:2015-03-23 03:16:40

标签: java recursion

问题是通过在java中使用递归按字母顺序对给定的字符串字母进行排序,例如:

input: "hello"
output: ehllo

我试过这段代码:

public class MinSort {

    public static void main(String[] args) {    
        System.out.println(sort("hello"));
    }

    static String temp="";
    static String answer ="";
    public static String sort(String s)
    {
        temp = s.substring(0, 1);
        if(s.length()<=1||s==null)
        {
            return s;
        }           
        else 
        {
            if(temp.compareTo(s.substring(1, 2))>1)
            {
                answer+=s.substring(0, 1);              
            }

            else 
            {
                answer += temp;
                temp = s.substring(1, 2);               
            }           

            sort(s.substring(0, s.length()-1));           
            return answer;
        }
    }
}

3 个答案:

答案 0 :(得分:2)

您没有找到第一个字符(按升序排列)。您应遍历整个字符串,如此递归selection sort(添加printf以显示迭代):

String ssort(String s) {
    if (s.length() < 2) {
        return s;
    }

    int pos = 0;
    char min = s.charAt(0);
    for(int i = 1; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c < min) {
            min = c;
            pos = i;
        }
    }

    System.out.printf("%c | %s\n", min, s.substring(0, pos) + s.substring(pos + 1));

    return min + ssort(s.substring(0, pos) + s.substring(pos + 1));
}

这样ssort("hello")就会产生:

e | hllo
h | llo
l | lo
l | o
ehllo

ssort("uioea")产生:

a | uioe
e | uio
i | uo
o | u
aeiou

答案 1 :(得分:1)

以下是如何在一行中完成的:

String output = Arrays.stream(input.split("")).sorted().collect(Collectors.joining(""));

如果这是真正的代码(而不是家庭作业),我将如何实现它。


一些测试代码:

String input = "hello";
String output = Arrays.stream(input.split("")).sorted().collect(Collectors.joining(""));
System.out.println(output);

输出:

ehllo

答案 2 :(得分:1)

我尝试了另一种方法,可能不是有效的方法,但能够得到结果。

  public class MinSort {

    public static void main(String[] args) {

        //System.out.println(sort("hello",0,"hello".length()-1));

        char ans[] =sort("hello",0,"hello".length()-1);
        StringBuilder strBuild = new StringBuilder();
        for (int i = 0; i < ans.length; i++) {

            strBuild.append(ans[i]);
        }

        System.out.println(strBuild.toString());        

    }   


    public static char[] sort(String s, int low, int high)
    {
        char[] ch = s.toCharArray();
        if(low<high)
        {


        int indexOfMin = low;
        char lowest = ch[0];
        for (int i = indexOfMin+1; i < high; i++) {

            if(ch[i]<lowest)
            {
                lowest = ch[i];
                indexOfMin = i;

            }

          }

        ch[indexOfMin]=ch[low];
        ch[low]=lowest;

         sort(s, low + 1, high);

        }

        return ch;


      }
  }
output: ehllo