In: Computer Science
Give pseudocode for a recursive function that sorts all letters in a string. For example, the string "goodbye" would be sorted into "bdegooy". Java
Function recursive_sort(array: char, length of array){
if (length== 1) then,
return;
for(i=0;i<n-1;i++){
current_character=array[i];
next_character=array[i+1];
if (current_character >next_character) then,
swap (array[i], array[i+1]);
}
recursive_sort(arr, length-1);
}
import java.util.*;
public class Solution{
//function to sort a character array recursively
public static void recursive_sort(char arr[],int n){
//base case
//if length of array is 1 then return
if (n==1){
return;
}
//to save adjacent character
char ch1,ch2;
for (int i=0;i<n-1;i++){
//adjacent character
ch1=arr[i];
ch2=arr[i+1];
//if character at ith is greater than character at (i+1)th
if(ch1 > ch2){
//then swap them
char temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
//call function recursively with length-1
recursive_sort(arr, n-1);
}
//driver function
public static void main(String []args){
//sample string
String s="goodbye";
//before
System.out.println(s);
//string to character array
char[] arr = s.toCharArray();
//call function
recursive_sort(arr,s.length());
//char array to string
s=String.valueOf(arr);
//after
System.out.println(s);
}
}
goodbye
bdegooy
CODE
OUTPUT
So if you still have any doubt regarding this solution please feel free to ask it in the comment section below and if it is helpful then please upvote this solution, THANK YOU.