public class InsertionSort {
public static int[] insertionSort(int[] array) {
for (int i = 1; i < array.length; i++) {
//索引j元素和之前的所有元素比较,小值在前
//每趟排序能通过排除非最大值法确定一个最大值,类似于冒泡排序
for (int j = i; j > 0; j--) {
if (array[j] < array[j - 1]) {
int temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
return array;
}
}
测试类:
public class TestSort {
int[] array = {3, 1, 6, 7, 8, 5, 2, 4};
//插入排序
@Test
public void insertionSort() {
int[] sort = InsertionSort.insertionSort(array);
for (int i : sort) {
System.out.println(i);
}
}
}
|