1.结束条件:
当指向无序序列的索引大于数组的长度-1的时候。
java实现
package com.jue.insertsort;
public class TestInsertSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int data[] = { 4, 3, 5, 6, 1, 8, 7, 9, 2 };
insertSort(data, 0);
}
public static void insertSort(int data[], int index) {
if (index > data.length - 1) {
return;
}
int tempIndex = index;
for (int i = tempIndex - 1; i >= 0; i--) {
if (data[i] <= data[tempIndex]) {
break;
} else {
final int tempData = data[i];
data[i] = data[tempIndex];
data[tempIndex] = tempData;
tempIndex = i;
}
}
index++;
insertSort(data, index);
}
}
非递归实现
public class InsertSort {
public static void main(String[] args) {
int[] datas = {9,8,7,6,5,4,3,2,1};
logs("new ", datas);
insertSort(datas);
logs("old ", datas);
}
public static void insertSort(int[] datas) {
for(int i = 1; i < datas.length; i ++) {
for(int j = i - 1; j >= 0; j --) {
if (datas[j + 1] < datas[j]) {
int temp = datas[j];
datas[j] = datas[j + 1];
datas[j + 1] = temp;
} else {
break;
}
}
logs( " ( " + i + " ) ", datas);
}
}
static void logs(String str, int[] data) {
StringBuffer sb = new StringBuffer(str);
for (int value : data) {
sb.append(value + " ");
}
System.out.println(sb);
}
}
输出