插入排序的原理是对数组中的第i个元素,认为它前面的i-1个已经排序好,然后将它插入到前面的i-1个元素中。插入排序对少量元素的排序较为有效.
代码:
package com.shen.maopao; public class MaoPao { public static void main(String[] args) { int[] a={1,4,5,1,0,88,98,232,22,222}; insertSort(a); for(int i=0;i<a.length;i++){ System.out.print(" " +a[i]); } } public static void insertSort(int[] a){ for(int i=1;i<a.length;i++) { int key=a[i]; int j=i-1; while(j>=0&&a[j]>key) { a[j+1]=a[j]; j--; } a[j+1]=key; } } }
运行结果: 0 1 1 4 5 22 88 98 222 232