1, when the elements are arranged, the elements need to be compared, so the comparable<t> interface needs to be implemented. That is, <t extends Comparable<t>>. Further, if the type to be compared can be compared with its parent type, it needs to be written as: <t extends comparable<? Super T>, wherein <? Super T> represents any super class of T.
The 2,insertionsortarray.java class enables you to sort data from small to large in order to insert a sort.
The 3,insertionsort method is responsible for sorting each element, and the Insertinorder method inserts the element to be sorted into the appropriate position, which is equivalent to performing a specific operation.
The specific code is as follows:
Public classInsertionsortarray { Public Static<textendscomparable<?SuperT>>voidInsertsort (t[] A,intN) {Insertionsort (A,0, n-1);//sequence A is sorted with a starting index of 0 and the last element indexed as N-1 } //to perform an insert sort from index first to last Private Static<textendscomparable<?SuperT>>voidInsertionsort (t[] A,intFirstintLast ) { for(intunsorted = first + 1; Unsorted <= last; unsorted++) {//The first element in the insert sort is considered ordered, so start with the second elementT firstunsorted = a[unsorted];//get the elements to be sortedInsertinorder (Firstunsorted, A, first, unsorted-1);//insert it in the right place } } //inserts an element into a sequence that is already ordered, starting at begin, ending at end Private Static<textendscomparable<?SuperT>>voidInsertinorder (T element, t[] A,intBeginintend) { intindex =end; //the element to be inserted is then sequentially compared from backward to the sorted element until it finds an element smaller than it . while(Index >= begin && (Element.compareto (a[index)) < 0) ) {A[index+ 1] = A[index];//move the element back one bit, a[index+1] is actually elementindex--; } A[index+ 1] = element;//insert element in the appropriate position }}
4, we used generics when we implemented the sort. The advantage of using generics is that for any type of object, as long as it implements the comparable interface, it can be compared by calling the CompareTo method.
Therefore, it can also sort the objects of a custom type, as long as the class you define implements the comparable interface.
The following test class defines an array of type string and an integer type, and can be ordered by calling the Insert Sort method, with the following code:
Public classTestsort { Public Static voidMain (string[] args) {string[] arr= {"Hello", "World", "Hadoop", "HBase", "Hive"}; Insertionsortarray.insertsort (arr, arr.length); System.out.println ("String sort Result"); for(String Str:arr) System.out.println (str); integer[] Integer= {1,5,3,8,10,4}; Insertionsortarray.insertsort (integer, integer.length); System.out.println ("Integer Sort Result"); for(intI:integer) System.out.println (i); }}
Java implementation of inserting sorting algorithm