`

插入排序

 
阅读更多

 

网上有一个插入排序算法的视频 ( http://v.youku.com/v_show/id_XMjU4NTY5MzEy.html ),非常生动,于是就模拟该视频,写了下面的代码:

 

import java.util.Arrays;

public class InsertSort {
	public static void main(String[] args) {
		int[] datas = new int[] { 3, 0, 1, 8, 7, 2, 5, 4, 9, 6 };
		System.out.println("Before-->" + Arrays.toString(datas));
		for (int i = 0; i < datas.length - 1; i++) {
			if (datas[i] > datas[i + 1]) {
				transposition(datas, i, i + 1);
				for (int j = i; j > 1; j--) {
					if (datas[j] < datas[j - 1]) {
						transposition(datas, j, j - 1);
					}
				}
			}
		}
		System.out.println("After-->" + Arrays.toString(datas));
	}

	public static void transposition(int[] datas, int indexA, int indexB) {
		System.out.println("transposition " + datas[indexA] + " and " + datas[indexB]);
		int temp = datas[indexA];
		datas[indexA] = datas[indexB];
		datas[indexB] = temp;
	}
}
 
输出结果如下:
Before-->[3, 0, 1, 8, 7, 2, 5, 4, 9, 6]
transposition 3 and 0
transposition 3 and 1
transposition 8 and 7
transposition 8 and 2
transposition 2 and 7
transposition 2 and 3
transposition 8 and 5
transposition 5 and 7
transposition 8 and 4
transposition 4 and 7
transposition 4 and 5
transposition 9 and 6
transposition 6 and 8
transposition 6 and 7
After-->[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics