Algorithm description: For a given array, initially assume that the first record forms an ordered sequence and the rest are unordered sequences. Then, starting from the second record, the currently processed record is inserted into its previous ordered sequence according to the size of the record, until the last record is inserted into the ordered sequence.
Direct insertion sorting Java implementation tutorial
Example 1
public class Insert {public static void main(String[] args) {int a[] = {9,3,28,6,34,7,10,27,1,5,8};show(a); for (int i=1;i insertOne(a, i);}show(a);}static void show(int a[]){for (int i=0;i System.out.print(a[i]+" ");}System.out.println();}//Int the kth element into the previous ordered queue static void insertOne(int a[],int k){ for (int i=0;i<=k;i++){if(a[i]>=a[k]){int temp = a[k];//Put a[k] to an intermediate variable before moving//Move backwards from the number in front of the k position, until i position for (int j=k-1;j>=i;j--){a[j+1] = a[j];}a[i] = temp;//Put the value in the intermediate variable to a[i], and the value at i after moving is empty. }}}}}Example 2
package sorting;/** * Insert sort* Average O(n^2), best O(n), worst O(n^2); Space complexity O(1); Stable; Simple* @author zeng * */public class InsertionSort {public static void insertionSort(int[] a) {int tmp;for (int i = 1; i < a.length; i++) {for (int j = i; j > 0; j--) {if (a[j] < a[j - 1]) {tmp = a[j - 1];a[j - 1] = a[j];a[j] = tmp;}}}} public static void main(String[] args) {int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 };insertionSort(a);for (int i : a) System.out.print(i + " ");}}Summarize
The above is all about the Java programming implementation of the direct insertion sorting code example. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!