Directory (?) [+] Introduction to insert sort algorithm
The sorting algorithm is the simplest algorithm and the most basic algorithm. As the name suggests, inserting sort is to insert the element that is currently being sorted into a list that is already in order . A very vivid example is to grab a poker hand and insert it into the orderly poker in the left hand. The worst time to insert a sort is O (n2), so it is not an optimal sorting algorithm. The feature is simple, does not require extra storage space, and works well when the elements are small. Insert Sort algorithm Java implementation
There are many types of data in Java, we choose the simplest integer, but this is not a general. Even if the customized object, the implementation of the java.lang.Comparable, the corresponding greater than (>) and less than (<) for CompareTo can be.
Because of the frequent operation and the printing of arrays, write a small Array tool class first. The code is as follows:[Java] View Plain copy public class arrayutils { public static void printarray (Int[] array) { system.out.print ("{"); for (int i = 0; i < array.length; i++) { system.out.print (Array[i]) ; if (i < array.length - 1) { system.out.print (", "); } } &Nbsp; system.out.println ("}"); } }
From an array ofa secondelement to get the currently pending element and insert it into the child array before the current element until the end of the array. The Java implementation of the insert sort and the test code are as follows:[Java] View Plain Copy public class insertsorttest { public Static void insertsort (Int[] array) { if (array == null | | &NBSP;ARRAY.LENGTH&NBSP;<&NBSP;2) { return; } for (int i = 1; i < array.length; i++) { int currentValue = array[i]; int position = i; for (INT&NBSP;J&NBSP;=&NBSP;I&NBSP;-&Nbsp;1; j >= 0; j--) { if (Array[j] > currentvalue) { array[j + 1] = array[j]; position -= 1; } else { break; } } array[ position] = currentvalue; } } public static void Main (String[] args) { int[] array = { 3, -1, 0, -8, 2, 1 }; arrayutils.printarray (array); insertsort (Array); arrayutils.printarray ( Array); } }