码迷,mamicode.com
首页 > 编程语言 > 详细

求数组逆置(数组与指针实现)

时间:2017-03-24 13:35:25      阅读:519      评论:0      收藏:0      [点我收藏+]

标签:strong   line   数组   toc   tle   nbsp   ret   alt   .com   

数组逆置

??基本思路:

??将a[0]与a[n-1]对换,再将a[1]与a[n-2]对换…直到将a[int(n-1)]与a[int((n-1)/2)-1]对换。

??如图所示:
技术分享


??使用数组来实现:


  1. //数组实现逆置
  2. void conver_arr(int c,int a[])
  3. {
  4. int low =0;
  5. int high = c -1;
  6. for(int i =0; i < c/2; i++)
  7. {
  8. if(low < high)
  9. {
  10. int temp = a[c - i -1];
  11. a[c - i -1]= a[i];
  12. a[i]= temp;
  13. }
  14. }
  15. }

??使用指针来实现:

  1. //指针实现逆置
  2. void conver_point(int c,int*a)
  3. {
  4. int*start;
  5. start = a;
  6. int*end;
  7. end= a + c -1;
  8. while(start <end)
  9. {
  10. int*temp =*start;
  11. *start =*end;
  12. *end= temp;
  13. *start++;
  14. *end--;
  15. }
  16. }

??其他代码:

  1. //打印输出信息
  2. void arr_print(int*a)
  3. {
  4. for(int i =0; i <10; i++)
  5. {
  6. printf("a[%d] = %d\n", i+1, a[i]);
  7. }
  8. }
  9. int main(void)
  10. {
  11. int arr_value[10]={12,34,5,67,3,54,6,31,46,1};
  12. int len =sizeof(arr_value)/sizeof(arr_value[0]);
  13. conver_arr(len, arr_value);
  14. conver_point(len, arr_value);
  15. arr_print(arr_value);
  16. return0;
  17. }

??运行结果如下图所示:
技术分享

 

求数组逆置(数组与指针实现)

标签:strong   line   数组   toc   tle   nbsp   ret   alt   .com   

原文地址:http://www.cnblogs.com/Bob-tong/p/6610833.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!