This article describes the method of implementing insertion sorting in Java. Share it for your reference. The specific implementation method is as follows:
import java.util.Arrays; /** * Algorithm name: Insert sort* Best efficiency O(n); Worst efficiency O(n²) is the same as bubble and selection, suitable for sorting small list* If the list is basically ordered , then insertion sorting is more efficient than bubble and selection. * @author L.Eric * */ public class insertionSorting { public static void main(String[] args) { //Define an integer array int[] nums = new int[]{4,3,-1,9, 2,1,8,0,6}; //Print the array System.out.println("Result before sorting:" + Arrays.toString(nums)); for(int index=0; index <nums.length; index++) { //Get the numerical value that needs to be inserted int key = nums[index]; //Get the index value int position = index; //Loop compare the previous sorted data and find a suitable place to insert while (position >0 && nums[position-1] > key) { nums[position] = nums[position-1]; position--; } nums[position] = key; } //Print the sorted result System.out .println("Sorted result:" + Arrays.toString(nums)); } }I hope this article will be helpful to everyone's Java programming.