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;
- }
posted on 2012-07-23 22:12
Daniel 閱讀(228)
評論(0) 編輯 收藏 所屬分類:
CoreJava