直接插入排序

        直接插入排序(Insertion Sort)的基本思想:每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的子序列中的适当位置,直到全部记录插入完成为止。

   设数组为a[0……n];

    此时将a[0]看作是一个有序的数组。然后将a[i]插入到前面a[0……i-1]之中。并行成一个新的有序数组。知道排序完成。

public class insert {

	void insert1(int[] a) {
		for (int i = 1; i < a.length - 1; i++) {
			if (a[i] < a[i - 1]) {
				int temp = a[i];
				int j = 0;
				for (j = i - 1; j >= 0 && a[j] > temp; j--) {
					a[j + 1] = a[j];
				}
				a[j + 1] = temp;
			}
		}
	}

	public static void main(String[] args) {
		int[] aa = { 2, 5, 1, 2, 6, 9, 8, 7, 4 };
		insert a = new insert();
		a.insert1(aa);
	}

}


你可能感兴趣的:(直接插入排序)