简体   繁体   中英

How to sort a word “hello” using recursion in java?

Problem is to sort the given letter of string alphabetically by using recursion in java, for example:

input: "hello"
output: ehllo

I have tried this code:

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;
        }
    }
}

You are not finding the first char (in ascending order). You should traverse the whole string, as in this recursive selection sort (added printf to visualize iterations):

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));
}

So that ssort("hello") yields:

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

and ssort("uioea") yields:

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

Here's how to do it in one line:

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

which is how I would implement it if this were real code (and not homework).


Some test code:

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

Output:

ehllo

I tried another approach, may not be efficient approach, but able to get the result.

  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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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