二、代码
package edu.hue.ds.sort;
import java.util.Random;
/**
* @author Don-Talk
* @createTime 2021年08月02日 12:50:00
* @Description 直接插入排序
*/
public class DerectlyInsertSort {
public static void main(String args[]){
int[] arr = new int[100]; //定义一个数组
int length = 15; //定义元素个数
Random random = new Random();
for(int i = 1 ; i<=length; ++i){ //从下标1开始存储
arr[i] = random.nextInt(100);
}
System.out.print("排序前数组为:");
showArray(arr,length);
insertSort(arr,length);
System.out.println();
System.out.print("排序后数组为:");
showArray(arr,length);
}
public static void insertSort(int[] arr,int length){ //for循环遍历未排序数组元素,while进行条件判断遍历已排序数组并进行后续操作
//遍历未排序数组元素,将元素插入已排序数组中
for(int i = 1; i<=length; ++i){
arr[0] = arr[i];
int j = i-1;
while (j>0 && arr[j] > arr[0]){
arr[j+1] = arr[j]; //②arr[j]位置元素比带插入元素值大,将arr[j]元素放到arr[j+1]
j--;
}
arr[j+1] = arr[0]; // ①找到arr[j]位置的元素比带插入元素值小,那么arr[j+1]就放入带插入元素
}
}
public static void showArray(int[] arr, int length){
for(int i = 1 ; i<=length; ++i){ //从下标1开始存储
System.out.print(arr[i]+" ");
}
}
}
三、运行结果