I wrote a recursive insertion method that inserts a number in a list of ascending numbers and reserves the list order. It's simple and it works, the problem is that it doesn't return the right list and duplicates it when the number I want to insert is higher than all the numbers in the list.
This is my code:
public static String insertNumber(String list, int numberToInsert, int startOfList, int endOflist) {
if (startOfList > endOflist) { // base case, reach end of the list
return list;
}
if (list.charAt(startOfList) == numberToInsert + '0') { // number already exist in list
System.out.println("No changes because " + numberToInsert + " exist in the list");
System.exit(0);
}
if (list.charAt(startOfList) > numberToInsert + '0') {
String s = Character.toString((char) (numberToInsert + '0'));
list = s + list.substring(startOfList);
return list;
}
return list.charAt(startOfList) + insertNumber(list, numberToInsert, startOfList + 1, endOflist);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a numerical ascending list and a number to insert: ");
String inputList = scan.next();
int numberToInsert = scan.nextInt();
String result = insertNumber(inputList, numberToInsert, 0, inputList.length() - 1);
System.out.println("The new list is: " + result);
}
This is the output I get for the following inputs:
Enter a numerical ascending list and a number to insert:
12567 3
The new list is: 123567
----------------------------------------------
Enter a numerical ascending list and a number to insert:
4567 1
The new list is: 14567
----------------------------------------------
Enter a numerical ascending list and a number to insert:
3456 9
The new list is: 34563456
I don't know where I went wrong.