设为首页 加入收藏

TOP

2.4.1 逆置数组项
2014-03-11 13:04:40 来源: 作者: 【 】 浏览:94
Tags:2.4.1

2.4  递归与数组

递归与数组

当使用数组时,递归是实用而强大的工具。我们将数组内容的逆置作为第一个示例,随后将关注涉及在数组中查找的几个问题。

2.4.1  逆置数组项

这个问题的解决方案与2.3.1节的第一个解决方案非常相似,在那里我们将字符串逆置。可以编写如下所示的伪代码:
 

  1. writeArrayBackward(anArray: char[])  
  2. if (the array is empty)  
  3. Do nothing -this is the base case  
  4. else  
  5. {  
  6. Write the last character in anArray  
  7. writeArrayBackward(anArray minus its last character)  

如何将anArray的最后一个字符去掉并将其传递给writeArrayBackward?可以传递数组中剩余字符的数量。在每次递归调用的时候,会将这个值减小1。另一种做法是传递最后一个字符的索引。也就是说,如果该索引为last,writeArrayBackward将对数组anArray[0..last]1执行操作,即anArray[0]到anArray[last]。递归调用将对子数组anArray[0..last-1]执行操作。这一思想更常见的版本是还传递第一个数组字符的索引。因此无须将这个索引假定为0,可以向writeArrayBackward传递数组anArry[first..last]。

函数writeArrayBackward的代码如下所示:
 

  1. /** Writes the characters in an array backward.  
  2. @pre  The array anArray contains size characters, where size >= 0.  
  3. @post  None.  
  4. @param anArray  The array to write backward.  
  5. @param first  The index of the first character in the array.  
  6. @param last  The index of the last character in the array. */  
  7. void writeArrayBackward(const char anArray[], int first, int last)  
  8. {  
  9. if (first <= last)  
  10. {  
  11. // Write the last character  
  12. cout << anArray[last];  
  13. // Write the rest of the array backward  
  14. writeArrayBackward(anArray, first, last - 1);  
  15. }   // end if  
  16. // first > last is the base case - do nothing  
  17. }   // end writeArrayBackward 

问题4 在前面的writeArrayBackward定义中,当first的值超过last的值时,为什么会到达基例。

问题5 编写一个递归函数,计算并返回数组中前n个(n ≥ 1)实数的乘积。

问题6 说明上个问题中的函数是如何满足递归函数标准的。

问题7 编写一个递归函数,计算并返回数组anArray[first..last]中整数的乘积。
 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.3 执行动作的递归(3) 下一篇2.4.2 折半查找(1)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·HTTPS 详解一:附带 (2025-12-26 02:20:37)
·TCP/IP协议到底在讲 (2025-12-26 02:20:34)
·TCP和UDP在socket编 (2025-12-26 02:20:32)
·有没有适合新手练习 (2025-12-26 01:48:47)
·用清华镜像网怎么下 (2025-12-26 01:48:44)