一. 插入排序
1.排序流程图
2. java程序实现
/**
* @author charles
* @createTime 2020/6/12 23:52
* @description 插入排序(升序排序)
*/
public class InsertSort {
public static int[] sort(int[] array){
if (array.length < 2){
return array;
}
// 已经被排序的索引,最后是待插入的前一个位置
int index;
// 待插入的值(等待被排序的值)
int currentValue;
for (int i = 0; i < array.length - 1; i++) {
index = i;
currentValue = array[i + 1];
// 把带插入的值 与前面已经排好的数组逐个进行比较 ,
// 如果带插入值小于排好序的某一个值,那就把这个值向后移动位,继续比较;
// 直到带插入的值 不在小于已经排好序的某一个值 ,那么带插入的值就需要插入这个值的后面
while (index >= 0 && currentValue < array[index]){
// 待插入的值小于 当前值 把当前值向后移动
array[index + 1] = array[index];
index --;
}
// 找到带插入的位置 插入值
array[index + 1] = currentValue;
}
return array;
}
public static void main(String[] args) {
int[] arr = {20, 90, 60, 50, 40, 30, 70, 80, 100, 10};
int[] sort = sort(arr);
System.out.println(Arrays.toString(sort));
}
}
未完待续。。。。。。