反转阵列 [英] Reversing an array In place

查看:121
本文介绍了反转阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我尝试打印和数组,然后反向使用另一个数组,但是我试图创建一个For Loop,它将使用一个数组并反转所有元素到位,而无需我经历创建全新数组的过程.

Okay so I've tried to print and Array and then reverse is using another array But I'm trying to create a For Loop that will take an array and reverse all of the elements in place without me having to go through the process of creating an entirely new array.

我的for循环遇到了一些问题,我不确定该从哪里去...我正在使用i将元素移到末尾并将其移到前面,然后将j用作一个计数器来跟踪元素...如果有更简单的方法可以做到这一点,任何建议将不胜感激.

My for loop is running into some problems and I'm not sure where to go from here...i'm using i to take the element at the end and move it to the front and then j is being used as a counter to keep track of the elements...if there is an easier way to do this Any suggestions would be appreciated.

我是这种编程语言的新手,所以非常感谢您提供任何其他信息.

I'm New to this programming language so any extra info is greatly appreciated.

#include <stdlib.h>
#include <time.h>

int Random(int Max) {
  return ( rand() % Max)+ 1;
}

void main() {
  const int len = 8;
  int a[len];
  int i;
  int j = 0;
  Randomize() ;

  srand(time(0));
  //Fill the Array
  for (i = 0; i < len; ++i) {
    a[i] = rand() % 100;
  }

  //Print the array after filled
  for (i = 0; i < len; ++i) {
    printf("%d ", a[i]);
  }
  printf("\n");
  getchar();

  //Reversing the array in place.
  for (i = a[len] -1; i >= 0, --i;) {
    a[i] = a[j];
    printf("%d ", a[j]);
    j++;
  }


}

推荐答案

while循环可能更容易概念化.可以认为这是从两端开始并交换两个元素,直到碰到中间为止.

A while loop may be easier to conceptualize. Think of it as starting from both ends and swapping the two elements until you hit the middle.

  i = len - 1;
  j = 0;
  while(i > j)
  {
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
    i--;
    j++;
  }

  //Output contents of now-reversed array.
  for(i = 0; i < len; i++)
    printf("%d ", a[i])

这篇关于反转阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆