First, insert sort introduction
Insert sort (Insertion sort) is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence, for unsorted data, to scan from backward forward in the sorted sequence, to find the appropriate position and insert it. The insertion sort is implemented on an implementation, usually in the order of In-place (that is, the ordering of extra space using only O (1), so that in the backward-forward scanning process, the ordered elements need to be moved back and forth gradually, providing the insertion space for the newest elements. time Complexity: O (n^2);
Algorithm Description:
1. Sorting starts with the second element, and the first element defaults to an ordered one.
2. Take the next element (the first takes the second, and so on, and so on), in the sequence of ordered elements (the default is the first element) from backward forward scanning
3. If the element (sorted) is greater than the new element, move the element to the next position
4. Repeat step 3 until the sorted element is found to be less than or equal to the position of the new element
5. After inserting a new element into the location
6. Repeat steps 2~5
Second, insert Sort implementation
PackageCom.roc.insertsort;/*** Direct Insert sort *@authorLIAOWP **/ Public classInsertsort { Public Static voidMain (string[] args) {int[] arr={5,7,3,9,1}; Insertsort.sort (arr); System.out.print ("Sort Result:"); for(inti = 0; i < arr.length; i++) {System.out.print (Arr[i]+" "); } } Public Static voidSortint[] arr) { if(arr==NULL|| ARR.LENGTH<2) {//if the number of arrays is less than 2, do not do what to do, directly return return; } for(inti = 1; i < arr.length; i++) {//To handle the case where the array needs to be returned, the I=1 default first number is an ordered sequence, and subsequent operations are based on the second number . intTemp=arr[i];//The default number of I is the middle number intpoint=i;//Record the subscript for(intj = i-1; J >= 0; j--) {//number of times to compare if(arr[j]>temp) {//if the number of J is greater than the middle numberARR[J+1]=ARR[J];//ExchangePoint-=1;//The index of the record minus}Else { Break; }} Arr[point]=temp;//Put the middle number in the label of the record for(intj = 0; J < Arr.length; J + +) {System.out.print (Arr[j]+" "); } System.out.println (); } }}
Iii. Summary
1, it is stable sort, does not change the same elements in the original order.
2, you can receive data edge sorting.
3, occupy small space, only need an additional memory space can be completed. O (1)
4, the idea is to play poker ideas.
Insert sort of Java base algorithm