# 排序算法之插入排序（Java）

xiaoxiao2021-02-28  23

Java代码实现：

public class SortTestTest { SortTest st = new SortTest(); Scanner sc = new Scanner(System.in); String a[] = null; @Test public void testDirectSort() { System.out.println("请输入想要排序的数字串，数字之间以逗号分隔："); String input = sc.nextLine(); a = input.split(","); st.directSort(a); } @Test public void testHillSort() { System.out.println("请输入想要排序的数字串，数字之间以逗号分隔："); String input = sc.nextLine(); a = input.split(","); st.hillSort(a); } } public class SortTest { // 直接插入排序 public void directSort(String array[]) { System.out.println("原序列如下："); for (int i = 0; i < array.length - 1; i++) { System.out.print(array[i] + ","); } System.out.println(array[array.length - 1]); for (int i = 1; i < array.length; i++) { String copy = array[i]; int j; for (j = i - 1; j >= 0; j--) { if (Integer.parseInt(array[j]) > Integer.parseInt(copy)) { array[j + 1] = array[j]; } else { break; } } array[j + 1] = copy; } System.out.println("通过直接排序后："); for (int i = 0; i < array.length - 1; i++) { System.out.print(array[i] + ","); } System.out.println(array[array.length - 1]); } // 希尔插入排序 public void hillSort(String array[]) { System.out.println("原序列如下："); for (int i = 0; i < array.length - 1; i++) { System.out.print(array[i] + ","); } System.out.println(array[array.length - 1]); double n = array.length; // for (int k = 0; k < Integer.MAX_VALUE; k++) { while (true) { n = Math.ceil(n / 2); int n1 = (int) n; if (n1 > 0) { for (int i = 0; i < array.length - n1; i++) { if (Integer.parseInt(array[i]) > Integer.parseInt(array[i + n1])) { String m = array[i + n1]; array[i + n1] = array[i]; array[i] = m; } } if (n1 == 1) { break; } } } System.out.println("通过希尔排序后："); for (int i = 0; i < array.length - 1; i++) { System.out.print(array[i] + ","); } System.out.println(array[array.length - 1]); } }