如果您发现解答中出现错误、对于没有给出解答的题目你有好的答案或者解答有改进的地方,只要您觉得有问题的地方,您可以通过xiezhenjiang@foxmail.com和我联系,谢谢!
先给出课本中归并排序的C语言实现吧:
- #include <stdio.h>
- #include <limits.h>
- void merge_sort(int *A, int p, int r);
- void merge(int *A, int p, int q, int r);
- int main(int argc, char *argv[])
- {
- int i;
- int A[9] = {1,5,7,8,2,4,6,9, -1};
- merge_sort(A, 0, 8);
- for(i = 0; i < 9; i++)
- {
- printf("%d ", A[i]);
- }
- return 0;
- }
- void merge_sort(int *A, int p, int r)
- {
- int q;
- if(p < r)
- {
- q = (p + r) / 2;
- merge_sort(A, p, q);
- merge_sort(A, q+1, r);
- merge(A, p, q, r);
- }
- }
- void merge(int *A, int p, int q, int r)
- {
- int length_l = q - p + 1;
- int length_r = r - q;
- int i,j,k;
- int *L = (int *)malloc( (length_l + 1) * sizeof(int) );
- int *R = (int *)malloc( (length_r + 1) * sizeof(int) );
- for(i = 0; i < length_l; i++)
- {
- L[i] = A[p+i];
- }
- for(i = 0; i < length_r; i++)
- {
- R[i] = A[q+1+i];
- }
- L[length_l] = INT_MAX;
- R[length_r] = INT_MAX;
- i = j = 0;
- for(k = p; k <= r; k++)
- {
- if(L[i] <= R[j])
- {
- A[k] = L[i];
- i++;
- }
- else
- {
- A[k] = R[j];
- j++;
- }
- }
- free(L);
- free(R);
- }
2.3-1 这个参照课本即可
2.3-2 直接给出C代码实现
- void merge2(int *A, int p, int q, int r)
- {
- int length_l = q - p + 1;
- int length_r = r - q;
- int i,j,k;
- int *L = (int *)malloc( (length_l) * sizeof(int) );
- int *R = (int *)malloc( (length_r) * sizeof(int) );
- for(i = 0; i < length_l; i++)
- {
- L[i] = A[p+i];
- }
- for(i = 0; i < length_r; i++)
- {
- R[i] = A[q+1+i];
- }
- i = j = 0;
- k = p;
- while(i < length_l && j < length_r)
- {
- if(L[i] <= R[j])
- {
- A[k++] = L[i++];
- }
- else
- {
- A[k++] = R[j++];
- }
- }
- while(i < length_l)
- {
- A[k++] = L[i++];
- }
- while(j < length_r)
- {
- A[k++] = R[j++];
- }
- free(L);
- free(R);
- }
2.3-3 略
2.3-4
2.3-5二分查找的C代码实现:
- #include <stdio.h>
- int binary_search(int *A, int n, int v);
- int main(int argc, char *argv[])
- {
- int A[9] = {0,1,2,3,4,5,6,7,8};
- int re;
- re = binary_search(A, 9, -3);
- printf("%d\n", re);
- return 0;
- }
- int binary_search(int *A, int n, int v)
- {
- int low = 0;
- int high = n;
- int mid;
- while(low < high)
- {
- mid = (low + high) / 2;
- if(A[mid] == v)
- {
- return mid;
- }
- else if(A[mid] < v)
- {
- low = mid + 1;
- }
- else
- {
- high = mid - 1;
- }
- }
- return -1;
- }
2.3-6 不能,其改善的这是查找中比较的次数,但当它找到了要插入的位置时,其移动数据的次数还是不能减少的,所以时间改善不了。
2.3-7 伪代码如下:
- int equal_x(int *A, int n, int x)
- {
- merge_sort(A,0, n – 1);
- for(i = 0; i < length(A); i++)
- {
- if(binary_serach(A, n, x – A[i] ) != –1)
- {
- return true;
- }
- }
- return false;
- }