像摸扑克牌一样的插入排序:
private static void insertSort(int[] a) {
int[] b = new int[a.length];
b[0] = a[0];
for (int n = 1, index = 0; n < a.length; n++, index = 0) {// n为b中待排的位置
// 找到插入到b[]中的位置
for (int i = 0; i < n; i++) {
if (a[n] > b[i])
index = i + 1;
}
// 插入到index位置
for (int i = n; i > index; i--) {
b[i] = b[i - 1];
}
b[index] = a[n];
}
bianLi(b);//遍历
}
private static void bianLi(int[] a) {
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i = 0; i < a.length; i++) {
if (i == a.length - 1)
sb.append(a[i]).append("]");
else
sb.append(a[i]).append(",");
}
System.out.println(sb);
}
|
|