Algorithm Description:
First, take a description of the language:
If you are doing a descending sort, scan each number from the beginning, and compare each number to the number in front of it, and directly find the number B that is less than the current number a (the current number is replaced by a) and B (the number less than a is replaced by a). The number A is then inserted into the position of Math B. Move the number B to the number a before the number a bit backwards. At this point, the sort ends.
The language expression actually understands this algorithm the person can understand, does not understand this algorithm the person is not too easy to understand, therefore still is the example to do the explanation:
For example there is an array of int[] Arraydata = {5, 9, 6, 7, 4, 1, 2, 3, 8}, altogether 9 elements.
Suppose it is a descending sort.
First scan the second number, let it compare with the number in front of it, when the first two number is {5,9},9 greater than 5, then put 9 into the position of 5 is arraydata[0], 5 and then moved to Arraydata[1]
Then scan the third number, this time because the first three number is the previous sort so {9,5,6}, take 6 first compared with the previous 5, greater than 5, then the forward scan, and 9 comparison, found less than 9, then we put 6 into the position of 5 is arraydata[1], 5 and then moved to Arraydata [2].
Scan the fourth number again, then the first four numbers become {9,6,5,7}, compare the 7 forward scan, and finally insert 7 into the 6 position i.e. arraydata[1], then 6 and then move to arraydata[2],5 and then move to Arraydata[3]
And so on, the result is finally reached.
Complexity of the algorithm:
O (N2)
Complexity of space:
O (1)
Code:
Languages used: Java
/* Insert Sort */public class Insertionsorting {public static void main (string[] args) {int[] Arraydata = {5, 9, 6, 7, 4, 1, 2 , 3, 8};insertionsortingmethod (Arraydata); for (int integer:arraydata) {System.out.print (integer); System.out.print ("");}} public static void Insertionsortingmethod (int[] arraydata) {int temp;int index;for (int i = 1; i < arraydata.length; i++ {temp = Arraydata[i];index = i-1;while (index >= 0 && Arraydata[index] < temp) {Arraydata[index + 1] = a rraydata[index];index--;} Arraydata[index + 1] = temp;}}}
Results:
Argument algorithm complexity: Because it is a double loop, the worst algorithm complexity is O (N2).
Argument space complexity: Because the data exchange as a temporary space is a few constants, so the spatial complexity is O (1)
Hark data structure and algorithm practice insert sort