Chapter 2
# Include <stdio. h> # Include <Stdlib. h> # Include <Time. h> // Insert sort Void Insertsort ( Int A [], Int N ){ Int I, j, key; For (I = 1 ; I <n; I ++ ) {Key =A [I]; j = I- 1 ; While (A [J]> key & J> = 0 ) {A [J + 1 ] = A [J]; j -- ;} A [J + 1 ] = Key ;}} // Recursive insertion sorting Void Insertsortd ( Int A [], Int N ){ Int I; Int Itemp; If (N> 1 ) {Insertsort (A, n - 1 ); Itemp = A [n- 1 ]; For (I = N- 2 ; I> = 0 & A [I]> itemp ;-- I) A [I + 1 ] = A [I]; A [I + 1 ] = Itemp ;}} // Binary Search of iteration Int Binarysearch ( Int A [], Int N, Int X ){ Int Low; Int High; Int Mid; low = 0 ; High = N- 1 ; While (Low <= High) {mid = Low + (high-low )/ 2 ; If (X = A [Mid]) Return Mid; Else If (A [Mid]> X) high = Mid- 1 ; Else Low = Mid + 1 ;} Return -1 ;} // Recursive binary LookupCode Int Binarysearch2 ( Int A [], Int Low, Int High, Int X ){ Int Mid; If (Low> High) Return - 1 ; Mid = Low + (high-low )/ 2 ; If (A [Mid] < X) Return Binarysearch2 (A, Mid + 1 , High, X ); Else If (A [Mid]> X) Return Binarysearch2 (A, low, mid-1 , X ); Else Return Mid ;} Int Main (){ Int I; Int A [ 10 ]; Srand (Time (null )); For (I = 0 ; I < 10 ; ++I) {A [I] = Rand () % 20 ; Printf ( " % D " , A [I]);} printf ( " \ N " ); Insertsort (, 10 ); For (I = 0 ; I <10 ; ++ I) printf ( " % D " , A [I]); printf ( " \ N " ); Printf ( " % D \ n " , Binarysearch2 (, 0 , 9 , 6 )); Return 0 ;}
// Binary insertion sorting # Include <stdio. h> # Include <Stdlib. h> # Include < String . H> # Include <Time. h> // Iterative binary search finds the first position not less than X Int Binarysearch ( Int A [], Int N, Int * I, Int X ){ Int Low; Int High; Int Mid; low = 0 ; High = N- 1 ; While (Low <=High) {mid = Low + (high-low )/ 2 ; If (X = A [Mid]) { * I = Mid + 1 ; Return 1 ;} Else If (A [Mid]> X) high = Mid- 1 ; Else Low = Mid + 1 ;} * I = Low; Return 0 ;} // Binary insertion sorting Void Binaryinsertsort ( Int A [], Int N ){ Int I; Int IPOs; Int Itemp; For (I = 1 ; I <= N- 1 ; ++ I) {itemp = A [I]; binarysearch (A, I, & IPOs, itemp); memmove ( + IPOs + 1 , A + IPOs, (I-IPOS )*Sizeof ( Int ); A [IPOs] = Itemp ;}} Int Main (){ Int I; Int A [ 10 ]; Srand (Time (null )); For (I = 0 ; I < 10 ; ++I) {A [I] = Rand () % 20 ; Printf ( " % D " , A [I]);} printf ( " \ N " ); Binaryinsertsort (, 10 ); For (I = 0 ; I <10 ; ++ I) printf ( " % D " , A [I]); printf ( " \ N " ); Return 0 ;}