public class InsertionSort
{
/**
* 插入排序的基本思想是:每步将一个待排序的纪录,按其关键码值的大小插入前面已经排序的文件中适当位置上,
* 直到全部插入完为止。
*/
public static void sort(int[] arr)
{
for(int curr=1;curr<arr.length;curr++)
{
int index = curr;
for(int pre=curr-1; pre>=0; pre--)
{
if(arr[pre] > arr[index])
{
int tmp = arr[index];
arr[index] = arr[pre];
arr[pre] = tmp;
index-- ;
}
else
{
break;
}
}
}
}
public static void main(String[] args)
{
int[] arr = {7,6,9,2,1,10};
print(arr, "排序前:");
sort(arr);
print(arr, "排序后:");
}
private static void print(int[] arr,String msg)
{
System.out.println(msg);
for(int k : arr)
{
System.out.print(k + "\t");
}
System.out.println();
}
}
输出结果:
排序前:
7 6 9 2 1 10
排序后:
1 2 6 7 9 10