posts - 1,  comments - 25,  trackbacks - 0

2.1-1这题可以参照书上17自己给出过程,这里就略去了。

2.1-2 先给出书上insertion-sort的C源代码吧,然后再给出按照非升序的代码:

课本中(非降序的)insertion-sort代码:

 

  1. void insertion_sort(int *A, int n)  
  2. {  
  3.     int i,j;  
  4.     int key; 
  5.  
  6.     for(i = 1; i < n; i++)  
  7.     {  
  8.         j = i - 1;  
  9.         key = A[i]; 
  10.  
  11.         while(j >= 0 && A[j] > key)  
  12.         {  
  13.             A[j+1] = A[j];  
  14.             j = j - 1;  
  15.         } 
  16.  
  17.         A[j+1] = key;  
  18.     }  

 

在这题中,只要讲非降序改成非升序排序,所以改后代码如下:

 

  1. void insertion_sort(int *A, int n)  
  2. {  
  3.     int i,j;  
  4.     int key; 
  5.  
  6.     for(i = 1; i < n; i++)  
  7.     {  
  8.         j = i - 1;  
  9.         key = A[i]; 
  10.  
  11.         while(j >= 0 && A[j] < key)  
  12.         {  
  13.             A[j+1] = A[j];  
  14.             j = j - 1;  
  15.         } 
  16.  
  17.         A[j+1] = key;  
  18.     }  

 

2.1-3这题给出伪代码:

 

  1. int find(int *A , int n, int v) 
  2.  
  3.  
  4.     int  i = 0; 
  5.  
  6.     for( ; i < n; i++) 
  7.  
  8.     { 
  9.  
  10.         if(v == A[i]) 
  11.  
  12.             return i; 
  13.  
  14.     } 
  15.  
  16.   
  17.  
  18.     return NIL; 
  19.  

 

2.1-4直接给出代码:

 

  1. /*在A[]和B[]中,数组的最低位对应与二进制的高位,即如果一个二进制数是011100,用数组表示就是A[] = {0,1,1,1,0,0}*/ 
  2.  
  3. void add(int *A ,int *B, int *C, int n)  
  4. {  
  5.     int i, a, c = 0;  
  6.     int s;  
  7.     for(i = n - 1; i >= 0 ; i--)  
  8.     {  
  9.         s = A[i] + B[i];  
  10.          
  11.         C[i+1] = (s + c) % 2;  
  12.         c = (s + c) / 2;  
  13.     } 
  14.  
  15.     C[0] = c;  

 

posted on 2012-07-23 22:12 Daniel 阅读(203) 评论(0)  编辑  收藏 所属分类: CoreJava

只有注册用户登录后才能发表评论。


网站导航:
 
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(3)

随笔档案

文章分类

文章档案

相册

搜索

  •  

最新评论