Perfect interpretation of java insertion sort

package com.kaige.demo;
/**
* Insertion sort (use scenario, sort below 7 elements)
* */
public class straight_insertion_sort {
public static void InsertSort(int [] arr){
int i,j;//two Int type variables
int n=arr.length;//array length
int target;//temporary value
for(i=1;i<n;i++){
j=i;
target=arr[i];
while(j> 0&&target<arr[j-1]){
arr[j]=arr[j-1];//When the temporary value is less than the previous element value, transpose
j--;
}
arr[j]=target;
}
}

/**
* arr={3,1,6,4};
* First analysis: j=i=1;target=arr[1]=1; satisfy the while condition j>0&&1<3; shift arr [1]=arr[0] -> 1364
* Second analysis: j=i=2;target=arr[2]=6; does not satisfy while; can get 1364;
* 第三次分析:j=i=3;target=arr[3]=4; 满足while条件j>0&&4<6;移位 arr[3]=arr[2] -> 1346
* */
public static void main(String[] args) {
int[] arr={3,1,6,4};
InsertSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326067494&siteId=291194637