Truth & Free

The truth shall make you free.

   :: 首页  :: 新随笔  ::  ::  :: 管理
算法描述:对于给定的一个数组,初始时假设第一个记录自成一个有序序列,其余记录为无序序列。接着从第二个记录开始,按照记录的大小依次将当前处理的记录插入到其之前的有序序列中,直至最后一个记录插入到有序序列中为止。
package sorting;

/**
 * 插入排序 
 * 平均O(n^2),最好O(n),最坏O(n^2);空间复杂度O(1);稳定;简单
 * @author zeng
 *
 */
public class InsertionSort {

	public static void insertionSort(int[] a) {
		int tmp;
		for (int i = 1; i < a.length; i++) {
			for (int j = i; j > 0; j--) {
				if (a[j] < a[j - 1]) {
					tmp = a[j - 1];
					a[j - 1] = a[j];
					a[j] = tmp;
				}
			}
		}
	}

	public static void main(String[] args) {
		int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 };
		insertionSort(a);
		for (int i : a)
			System.out.print(i + " ");
	}
}

  

posted on 2015-04-25 21:18  andyzeng24  阅读(15732)  评论(0编辑  收藏  举报