One
//Direct Insert Sort//idea: Take an orderly queue first, then sort the other numbers one by one and this ordered sequence//Stable//time Complexity best case: O (n) worst case O (n²)//space complexity O (n) Public classInsertalgorithm {Static int[] arr={5,7,3,9,10,50}; Public voidsort () { for(inti=0;i<arr.length-1;i++){ for(intj=0;j<i;j++){ if(arr[i]>Arr[j]) { } Else{ intTemp=0; Temp=Arr[i]; Arr[i]=Arr[j]; ARR[J]=temp; } } } } Public Static voidMain (string[] args) {Insertalgorithm ia=NewInsertalgorithm (); Ia.sort (); for(inti=0;i<arr.length;i++) {System.out.println (arr[i]); } }}
Second, insert sort-hill sort
- Select an incremental sequence T1,T2,...,TK, where ti>tj,tk=1;
- According to the number of increment series K, the sequence is sorted by K-trip;
- Each order, according to the corresponding increment ti, the backlog sequence is divided into several sub-sequences of length m, respectively, the sub-table is directly inserted sort. Only the increment factor is 1 o'clock, the entire sequence is treated as a table, and the length of the table is the length of the entire sequence.
voidPrintintA[],intNinti) {cout<<i << ":"; for(intj= 0; j<8; J + +) {cout<<A[J] << ""; } cout<<Endl; } /*** Direct Insert sort in general form * *@paramint DK Shrink increment, if direct insert sort, dk=1 **/ voidShellinsertsort (intA[],intNintDK) { for(intI= DK; i<n; ++i) { if(A[i] < A[I-DK]) {//if the first element is greater than the i-1 element, it is inserted directly. Less then, move the ordered table after inserting intj = IDK; intx = A[i];//Copy as Sentinel, which stores the elements to be sortedA[i] = A[I-DK];//first move back one element while(x < a[j]) {//find the insertion position in an ordered tableA[J+DK] =A[j]; J-= DK;//element Move back} a[j+DK] = x;//Insert to correct position} print (A, n,i); } } /*** First by increment D (N/2,n is the number of orders to be sorted by Hill sort **/ voidShellsort (intA[],intN) { intDK = N/2; while(DK >= 1) {Shellinsertsort (A, n, DK); DK= DK/2; } } intMain () {intA[8] = {3,1,5,7,2,4,9,6}; //Shellinsertsort (a,8,1);//Direct Insert SortShellsort (a,8);//Hill Insert SortPrint (a,8,8); }
10 Basic sorting algorithms