如果您发现解答中出现错误、对于没有给出解答的题目你有好的答案或者解答有改进的地方,只要您觉得有问题的地方,您可以通过xiezhenjiang@foxmail.com和我联系,谢谢!
2-1 help me
2-2 给出冒泡排序的C语言实现吧,证明就略了:
- #include <stdio.h>
- void bubble_sort(int *A, int n);
- int main(int argc, char *argv[])
- {
- int i;
- int A[]={1,2,5,-1,3,55,-8,10,2};
- bubble_sort(A, 8);
- for(i = 0; i < 8; i++)
- {
- printf("%d ", A[i]);
- }
- return 0;
- }
- void bubble_sort(int *A, int n)
- {
- int i,j;
- for(i = 0; i < n; i++)
- {
- for(j = 0; j < n-i-1; j++)
- {
- if(A[j] > A[j+1])
- {
- A[j] = A[j] + A[j+1];
- A[j+1] = A[j] - A[j+1];
- A[j] = A[j] - A[j+1];
- }
- }
- }
- }
2.3
2)
- y = a0;
- e = 1;
- for(i = 1; i < n; i++)
- e = e *x;
- y = y + ai*e
- return y;
3)、4)证明略
2.4
a)(2,1)、(3,1)、(8,6)、(8,1)、(6,1)
b)当数组按递减顺序排列时,数组含有最多的逆序对。包好了n*(n-1)/2个逆序对
c)成正比
d)给出源代码:
- #include <stdio.h>
- #include <limits.h>
- int merge_sort(int *A, int p, int r);
- int merge2(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};
- int v;
- v = merge_sort(A, 0, 8);
- for(i = 0; i < 9; i++)
- {
- printf("%d ", A[i]);
- }
- printf("\n%d\n", v);
- return 0;
- }
- int merge_sort(int *A, int p, int r)
- {
- int q;
- int v = 0;
- if(p < r)
- {
- q = (p + r) / 2;
- v += merge_sort(A, p, q);
- v += merge_sort(A, q+1, r);
- v += merge2(A, p, q, r);
- }
- return v;
- }
- int 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 sum = 0;
- 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++];
- sum += length_r - j;/*这里是按非升序排列数组的,所以R[j]是R[]中第一个小于L[i],后面R[j+1]..R[length_r-1]都小于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);
- return sum;
- }
转载于:https://blog.51cto.com/charlesxie/793921