ITeye博客

插入排序

wlh269 · 2011-01-07 12:01 · Java算法 · 编程语言 · Markdown


package sort;
public class InsertSort {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int a[] = { 7, 8, 2, 5, 1 };
		sort(a);

	}

	public static void sort(int[] A) {
		//每一次循环就是找到下标为i的元素合适的位置,使它前面所有元素都比他小,如果比前面的元素小就和它交换位置
		for (int i = 1; i < A.length; i++) {
			if (A[i] < A[i - 1]) {
				int j = i - 1;
				int temp = A[i];

				do {
					A[j + 1] = A[j];
				} while (--j >= 0 && temp < A[j]);
				A[j + 1] = temp;
			}
		}
		for (int i = 0; i < A.length; i++) {
			System.out.print(A[i]);
			System.out.print(",");
		}
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。