2.3-1:
3 9 26 38 41 49 52 59
3 26 41 52 9 38 49 57
3 41 52 26 38 57 9 49
3 41 52 26 38 57 9 49
2.3-2: (merge Sort)
voidMergeSort (intA[],intLintR) { intm; if(L <r) {m= (L + r)/2; MergeSort (A, L, M); MergeSort (A, M+1, R); Merge (A, L, R, M); }}voidMergeintA[],intLintRintp) { intI, j, K; intN1 = P-l +1; intN2 = R-p; intlarray[n1], rarray[n2]; for(i=0; i<n1; i++) Larray[i] = a[l+i]; //for (i=0; i<n1; i++) printf ("%d", Larray[i]); for(j=0; j<n2; J + +) Rarray[j] = a[p+j+1]; //for (j=0; j<n2; j + +) printf ("%d", rarray[j]);i =0; J=0; for(k=l; k<=r; k++) { if(I < N1 && (J >= N2 | | larray[i] <=Rarray[j])) {A[k]=Larray[i]; ++i; } Else if(J < N2 && (i >= n1 | | rarray[j] <Larray[i])) {A[k]=Rarray[j]; ++J; } }}
View Code
2.3-3:
n=2:tn=2lg2=2
Assuming n=k, the equation is set.
tk+1=2 (Tk) + 2k+1=2 * (2k * k) + 2k+1=2k+1 (k+1)
2.3-4:
Worst case scenario:
1 n=2;
Tn = tn-1+n-1;
2.3-5: (Two-point search)
intBinarySearch (intA[],intVintN) { intL, R, M; L=0; R= N-1; while(L <=r) {m= (L + r)/2; if(v < a[m]) R = m-1; Else if(V > a[m]) L = m +1; Else returnm; } return-1;}
View Code
Worst case scenario:
2 n=2;
Tn=t (N/2) + 1 n=2k;
Θ (LGN)
2.3-6:
Unable to reduce run time
2.3-7: (Refer to the answer of netizens, do a bit of optimization, I hope you can make better suggestions for improvement)
Algorithm: asks if a set of n numbers contains and is 2 elements of X (need to support C99 standard)
BOOLSumX (intA[],intNintx) { intlength, complement[n]; MergeSort (A,0, N-1); Length=deduplication (A, n); Xcomplement (A, complement, length, x); returnMergesearch (A, complement, length);}BOOLMergesearch (intA[],intB[],intN) { intI, J; for(i=0, j=n-1; I<n && j>=0&& a[i]!=B[j];) if(A[i] < b[j]) i++; Elsej--; returnI<n && j>=0;}voidXcomplement (intA[],intAcomplement[],intNintx) { inti; for(i=0; i<n; i++) Acomplement[i] = x-a[i];}intDeduplication (intA[],intN) { intI, tmp[n]; intj =0; for(i=0; i<n; i++) { if(I >0&& a[i-1] = A[i]) J + +; TMP[J]=A[i]; } for(i=0; i<=j; i++) A[i] =Tmp[i]; returnj+1;}voidMergeSort (intA[],intLintR) { intm; if(L <r) {m= (L + r)/2; MergeSort (A, L, M); MergeSort (A, M+1, R); Merge (A, L, R, M); }}voidMergeintA[],intLintRintm) { intMax = +; intI, j, K; intN1 = M-l +1; intN2 = R-m; intlarray[n1+1], rarray[n2+1]; for(i=0; i<n1; i++) Larray[i] = a[l+i]; for(j=0; j<n2; J + +) Rarray[j] = a[m+j+1]; LARRAY[N1]=Max; RARRAY[N2]=Max; I=0; J=0; for(k=l; k<=r; k++) { if(I < N1 && Larray[i] <=Rarray[j]) {A[k]=Larray[i]; ++i; } Else{A[k]=Rarray[j]; ++J; } }}
View Code
Θ (NLGN)
Introduction to Algorithms (third edition) Exercises2.3