如果您發現解答中出現錯誤、對於沒有給出解答的題目你有好的答案或者解答有改進的地方,只要您覺得有問題的地方,您可以通過[email protected]和我聯繫 下面開始正題了:
2.1-1這題可以參照書上17自己給出過程,這裏就略去了。
2.1-2 先給出書上insertion-sort的C源代碼吧,然後再給出按照非升序的代碼:
課本中(非降序的)insertion-sort代碼:
- void insertion_sort(int *A, int n)
- {
- int i,j;
- int key;
- for(i = 1; i < n; i++)
- {
- j = i - 1;
- key = A[i];
- while(j >= 0 && A[j] > key)
- {
- A[j+1] = A[j];
- j = j - 1;
- }
- A[j+1] = key;
- }
- }
在這題中,只要講非降序改成非升序排序,所以改後代碼如下:
- void insertion_sort(int *A, int n)
- {
- int i,j;
- int key;
- for(i = 1; i < n; i++)
- {
- j = i - 1;
- key = A[i];
- while(j >= 0 && A[j] < key)
- {
- A[j+1] = A[j];
- j = j - 1;
- }
- A[j+1] = key;
- }
- }
2.1-3這題給出僞代碼:
- int find(int *A , int n, int v)
- {
- int i = 0;
- for( ; i < n; i++)
- {
- if(v == A[i])
- return i;
- }
- return NIL;
- }
2.1-4直接給出代碼:
- /*在A[]和B[]中,數組的最低位對應與二進制的高位,即如果一個二進制數是011100,用數組表示就是A[] = {0,1,1,1,0,0}*/
- void add(int *A ,int *B, int *C, int n)
- {
- int i, a, c = 0;
- int s;
- for(i = n - 1; i >= 0 ; i--)
- {
- s = A[i] + B[i];
- C[i+1] = (s + c) % 2;
- c = (s + c) / 2;
- }
- C[0] = c;
- }