[java]代码库
package insertionSort;
import java.util.Arrays;
public class TestInsertionSort {
public static void main(String[] args) {
int[] arr = {3,4,9,7,1,2,2,1,6,8,5};
System.out.println("The unsorted order arrays is : "+Arrays.toString(arr));
System.out.println("Algorithm directInsertaionSort - the sorted order arrays is : "+Arrays.toString(InsertionSortImpl.directInsertaionSort(arr)));
}
}
package insertionSort;
public class InsertionSortImpl {
public static int[] directInsertaionSort(int arr[]) {
int len = arr.length;
int temp;
int positionMark = -1;
for (int i = 1; i < len; i++) {
temp = arr[i];
for (int j = i - 1; j >= 0; j--) {
if (temp < arr[j]) {
arr[j + 1] = arr[j];
positionMark = j;
}else{
break;
}
}
if (positionMark != -1) {
arr[positionMark] = temp;
positionMark = -1;
}
}
return arr;
}
}
/***运行结果:
The unsorted order arrays is : [3, 4, 9, 7, 1, 2, 2, 1, 6, 8, 5]
Algorithm directInsertaionSort - the sorted order arrays is : [1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]
****/