import java.util.Arrays;
public class InsertionSort {
public static void main(String[] args) {
int[] array = new int[6];
for (int i = 0; i < 6; i++) {
array[i] = (int) (Math.random() * 100);
}
System.out.println("待排序的数据为:" + Arrays.toString(array));
System.out.println("开始排序*********");
insertionSort(array);
System.out.println("排序过后的数据为:" + Arrays.toString(array));
}
public static void insertionSort(int[] array) {
int len = array.length;
int temp = 0;
for (int i = 1; i < len; i++) {
temp = array[i]; //保存当前需要插入的值
for (int j = i - 1; j >= 0; j--) {
if (temp < array[j]) {
array[j + 1] = array[j];
if (j == 0) { //比所有数据都小,放在首位
array[0] = temp;
}
} else {
array[j + 1] = temp;
break;
}
}
}
}
}
双重for循环实现插入排序
最新推荐文章于 2023-10-09 09:53:30 发布