1 public class InsertSortTest{ 2 public static void InsertSort(int[] source) { 3 //默认第一个元素已排序 4 for (int i = 1; i < source.length; i++) { 5 for (int j = i; (j > 0) && (source[j] < source[j - 1]); j--) { 6 swap(source, j, j - 1); 7 } 8 } 9 } 10 //完成交换功能的子函数 static 11 private static void swap(int[] source, int x, int y) { 12 int temp = source[x]; 13 source[x] = source[y]; 14 source[y] = temp; 15 } 16 //在main中测试 17 public static void main(String[] args) { 18 int[] a = {4, 2, 1, 6, 3, 6, 0, -5, 1, 1}; 19 20 InsertSort(a); 21 22 for (int i = 0; i < a.length; i++) { 23 System.out.printf("%d ", a[i]); 24 } 25 } 26 }
#学习笔记,如有谬误,敬请指正。#