Insert Sort algorithm
Simple insertion Sorting algorithm principle: Select an element from the entire backlog to be inserted into an ordered subsequence, to get an ordered, element plus one subsequence, until the entire sequence of elements to be inserted is 0, then the entire sequence is all ordered.
In the actual algorithm, we often select the first element of the sequence as an ordered sequence (because an element is definitely ordered), and we gradually insert the subsequent elements into the ordered sequence in front, until the entire sequence is ordered.
Importjava.util.Arrays;/*[email protected] Zhang Zhaqi Direct Insertion Sort: The direct insertion sort is the selection of an element from the sequence to be sorted, inserted into an already ordered element, until all elements are inserted into the ordered sequence and all elements are in order. The common practice is to treat the first element as an ordered element (that is, the first element of the sequence to be sorted as an ordered sequence), and then we compare the second element with an ordered sequence (that is, the first element) and insert it into the sequence in the correct sequence. Then the third element is compared to the first two elements of the ordered sequence (that is, the entire sequence to be sorted), and the third one is inserted into the first two elements, making the first three elements orderly. And so on until all elements are ordered. */ Public classTest { Public Static voidMain (string[] args) {intarr[]={3,89,72,43,1}; System.out.println (arrays.tostring (arr)); //before sorting, the outputInsertsort (arr); System.out.println (arrays.tostring (arr)); //after sorting, the output } Private Static voidInsertsort (int[] arr) { intTemp//defines a temporary variable to store when exchanging data for(inti=1;i<arr.length;i++) {//because we're going to insert each element of the sequence to the previous ordered sequence, we'll iterate over the sequence . for(intj=0;j<i;j++) {//The second loop is used primarily to scan a sequenced sequence, compare the data to be inserted, and then decide where to insert it. if(Arr[i] <Arr[j]) {Temp=Arr[i]; Arr[i]=Arr[j]; ARR[J]=temp; } } } }}
Insert Sort Algorithm--java implementation