3.22

public class InsertSort {

public static void main(String[] args) {
int[] array = new int[]{2, 6, 3, 8, 9, 0, 1, 7, 4};
InsertSort(array);
}

public static void printArray(int[] array) {
for(int i : array) {
System.out.printf("%d\t", i);
}
System.out.println();
}

public static void InsertSort(int[] array) {
if( array == null) {
return;
}

for (int i = 1; i < array.length; i++) {
if( array[i] < array[i - 1]) {
int key = array[i];
int j;
for ( j = i - 1; j >= 0; j--) {
if ( key < array[j]) {
array[j + 1] = array[j];
} else {
break;
}
}
array[j + 1] = key;
}
printArray(array);
}
}
}

posted @ 2024-03-22 23:21  catsahsy  阅读(3)  评论(0编辑  收藏  举报