22)49O的8 162因25(9@9 16 25)25(49 i=5 08(四21(252549
i = 4 i = 5 21 25 25* 49 16 08 16 16 21 25 25* 49 08 16 21 25 25* 49 08 08 16 21 25 25* 49 08
Direct Insertion Sort Algorithm void Insertion Sort( ElementType A[], int N) ElementType Tmp; for(P=1;P≤N;P++){ Tmp=A[P]: the next coming card*/ for(j=P; j>0&&A[j-1]> Tmp; j-) A[j]=A[j-1]; shift sorted cards to provide a position for the new coming card"/ A[j]= Tmp;/ place the new card at the proper position*/ 3 /end for-P-loop * The worst case: Input al is in reverse order. T(N)=O(N2) The best case: Input al is in sorted order. T(N)=O(N)
Direct Insertion Sort Algorithm void InsertionSort ( ElementType A[ ], int N ) { int j, P; ElementType Tmp; for ( P = 1; P < N; P++ ) { Tmp = A[ P ]; /* the next coming card */ for ( j = P; j > 0 && A[ j - 1 ] > Tmp; j-- ) A[ j ] = A[ j - 1 ]; /* shift sorted cards to provide a position for the new coming card */ A[ j ] = Tmp; /* place the new card at the proper position */ } /* end for-P-loop */ } The worst case: Input A[ ] is in reverse order. T( N ) = O( N2 ) The best case: Input A[ ] is in sorted order. T( N ) = O( N )
)Binary Insertion sort Basic idea: there are number of n sequential objects vIOL vIIL,.,VIn-l in the seqlist, Insertion sort makes use of the fact that elements in position 0 through i-I are already in sorted order. use binary search to find the inserting position of vi when insert element vi Algorithm of binary insertion sort
➢Binary Insertion sort Basic idea: there are number of n sequential objects V[0], V[1], …, V[n-1] in the SeqList,Insertion sort makes use of the fact that elements in position 0 through i-1 are already in sorted order. use binary search to find the inserting position of V[i] when insert element v[i]. Algorithm of binary insertion sort
typedef int SortData; void BinInssort( SortData VI, int n)i SortData temp; int Left, Right; for(int i=l; i< n; i++)i Left=0; Right=i-1; temp= v; while( left < right)i int mid=( Left Right )/2 if( temp <VImid)right=mid-1 else Left= mid +1 for (int k=i-1; k>= Left; k--)VIk+1=VIk 记录后移 VLLeft=temp;插入
typedef int SortData; void BinInsSort ( SortData V[ ], int n ) { SortData temp; int Left, Right; for ( int i = 1; i < n; i++) { Left = 0; Right = i-1; temp = V[i]; while ( Left <= Right ) { int mid = ( Left + Right )/2; if ( temp < V[mid] ) Right = mid - 1; else Left = mid + 1; } for ( int k = i-1; k >= Left; k-- ) V[k+1] = V[k];// 记录后移 V[Left] = temp; //插入 } }
Binary insertion sort 234 5 temp 2(5 5 0 2 4 5 temp i=22( 3 i=4(34⑤2(8(8 i=5(3((8②0的 ③3④46(8662
Binary insertion sort 0 1 2 3 4 5 temp i = 1 i = 2 0 1 2 3 4 5 temp 5 21 3 3 i = 3 5 5 3 5 21 21 4 4 i = 4 3 5 21 8 8 i = 5 3 5 8 21 16 16 4 4 3 4 5 8 16 21