public class InsertionSort { private static int[] input; private static int length; public static void main(String[] args) { String inputString = "4143675351981074"; length = inputString.length(); input = new int[length]; for (int i = 0; i < length; i++) { input[i] = Character.getNumericValue(inputString.charAt(i)); } System.out.println("Unsorted list:"); printList(); System.out.println(); for (int i = 0; i < length; i++) { insert(input[i], i); printList(); System.out.println(); } System.out.println("Sorted list:"); printList(); } public static void insert(int removed_value, int removed_index) { if (removed_value <= input[0]) { for (int i = removed_index; i >= 1; i--) { input[i] = input[i - 1]; } input[0] = removed_value; } else { int i; for (i = 1; i < removed_index - 1; i++) { if (removed_value >= input[i - 1] && removed_value <= input[i]) { break; } } if (i < removed_index - 1) { for (int j = removed_index; j >= i; j--) { input[j] = input[j - 1]; } input[i] = removed_value; } else if (i == removed_index - 1) { if (input[removed_index - 1] > input[removed_index]) { int temp = input[removed_index - 1]; input[removed_index - 1] = input[removed_index]; input[removed_index] = temp; } } } } public static void printList() { for (int i = 0; i < input.length; i++) { System.out.print(input[i] + " "); } System.out.println(); } }
using System; public class InsertionSort { private static int[] input; private static int length; public static void Main() { String inputString = "4143675351981074"; length = inputString.Length; input = new int[length]; for (int i = 0; i < length; i++) { input[i] = (int)Char.GetNumericValue(inputString[i]); } Console.WriteLine("Unsorted list:"); printList(); Console.WriteLine(); for (int i = 0; i < length; i++) { insert(input[i], i); printList(); Console.WriteLine(); } Console.WriteLine("Sorted list:"); printList(); } public static void insert(int removed_value, int removed_index) { if (removed_value <= input[0]) { for (int i = removed_index; i >= 1; i--) { input[i] = input[i - 1]; } input[0] = removed_value; } else { int i; for (i = 1; i < removed_index - 1; i++) { if (removed_value >= input[i - 1] && removed_value <= input[i]) { break; } } if (i < removed_index - 1) { for (int j = removed_index; j >= i; j--) { input[j] = input[j - 1]; } input[i] = removed_value; } else if (i == removed_index - 1) { if (input[removed_index - 1] > input[removed_index]) { int temp = input[removed_index - 1]; input[removed_index - 1] = input[removed_index]; input[removed_index] = temp; } } } } public static void printList() { for (int i = 0; i < input.Length; i++) { Console.Write(input[i] + " "); } Console.WriteLine(); } }