`
wlh269
  • 浏览: 447872 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

插入排序

J# 
阅读更多
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(",");
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics