反转阵列到位

时间:2014-04-10 02:59:23

标签: c arrays

好吧所以我尝试打印和阵列然后反向使用另一个阵列但是我试图创建一个For循环,它将采用一个阵列并反转所有元素而不需要我完成创建一个全新阵列的过程。

我的for循环遇到了一些问题,我不知道从哪里开始......我使用i将元素移到最后并将其移到前面然后j被用作计数器来跟踪元素...如果有更简单的方法来做这个任何建议将不胜感激。

我是这种编程语言的新手,所以非常感谢任何额外的信息。

#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++;
  }


}

12 个答案:

答案 0 :(得分:5)

while循环可能更容易概念化。可以把它想象成从两端开始并交换两个元素直到你到达中间位置。

  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])

答案 1 :(得分:5)

void reverse_range(int* buffer, int left, int right)
{
    while (left < right)
    {
        int temp = buffer[left];
        buffer[left++] = buffer[right];
        buffer[right--] = temp;
    }
}

将其称为反向数组

int a[3] = {1, 2, 3};
reverse_range(a, 0, 2);

答案 2 :(得分:2)

你是在正确的轨道,但需要考虑最后一个循环多一点和内部的赋值操作。循环初始化已关闭,因为i = a[len] - 1会将最后一个条目的值复制到i。由于该值是随机数,因此您的索引可能会超出范围。

接下来,您将一半的阵列复制到另一半,然后再复制。该循环执行以下操作: a[7] = a[0] a[6] = a[1] a[5] = a[2] a[4] = a[3] ...

此时您已经丢失了[4]到[7]中的所有初始值。

试试这个:

for( i = 0; i < len / 2; i++ ){
    int temp = a[i];
    a[i] = a[len - i];
    a[len - i] = temp;
}

使用调试器并逐步循环观察itemp的值以及数组中的每个元素

答案 3 :(得分:1)

只是我的2美分......

#include <stdlib.h>
#include <stdio.h>

int main() {
      int arry[] = {0, 1, 2, 3, 4, 5};
      int* s = arry;
      int* e = arry + (sizeof(arry) / sizeof(arry[0])) - 1;
      while (s < e) {
        *e ^= *s;
        *s ^= *e;
        *e ^= *s;
        s++;
        e--;
      }
      for (size_t i = 0; i < (sizeof(arry) / sizeof(arry[0])); i++) {
        fprintf(stderr, "%d, ", arry[i]);
      }
      fprintf(stderr, "\n");
   }

答案 4 :(得分:0)

对于初学者而不是:

for (i = a[len] -1; i >= 0, --i;) {

你想要这个:

for (i = len-1; i >= 0, --i;) {

但你也只想进入数组的中途,所以它将是

for (i = len-1; i > j, --i;) {

答案 5 :(得分:0)

试试这个;

#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,end;
  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();

  for (i = 0; i < n/2; i++) {
      t = a[i];
      a[i]   = a[end];
      a[end] = t;
      end--;
  }

}

希望这有助于......:)

仅供参考。尝试使用有意义的变量名称而不仅仅是i,a...。这将有助于您在编写更大的代码时。 :)

答案 6 :(得分:0)

如果您对编写任何数字类型的函数不感兴趣,请尝试使用宏来执行此任务。此代码与任何内置数值类型相同:int,float,double。

它不支持字符串,因为任何字符串都以字符结尾为空字符&#39; \ 0&#39;。更多受控版本我的类似答案在https://stackoverflow.com/a/42063309/6003870,并包含反向字符串的解决方案。

完整代码

#include <stdio.h>

// print items of an array by a format
#define PRINT_ARRAY(array, length, format) \
{ \
    putchar('['); \
    for (size_t i = 0; i < length; ++i) { \
        printf(format, array[i]); \
        if (i < length - 1) printf(", "); \
    } \
    puts("]"); \
}


// reverse an array in place
#define REVERSE_ARRAY(array, length, status) \
    if (length > 0) { \
        for (int i = 0; i < length / 2; ++i) { \
            double temp; \
            temp = array[i]; \
            array[i] = array[length - i - 1]; \
            array[length - i - 1] = temp; \
        } \
        *status = 0; \
    } \
    else if (length < 0) *status = -1; \
    else *status = 1;

#define SUCCESS_REVERSE_ARRAY_MSG "An array succefully reversed"
#define FAILED_REVERSE_ARRAY_MSG "Failed reverse for an array"
#define NO_CHANGED_REVERSE_ARRAY_MSG "An array no changed"


/*
    Print message about status reverse an array
 */
static void
print_msg_reverse_array_status(const int status)
{
    if (status == 0) printf("Status: %s\n", SUCCESS_REVERSE_ARRAY_MSG);
    else if (status == -1) printf("Status: %s\n", FAILED_REVERSE_ARRAY_MSG);
    else if (status == 1) printf("Status: %s\n", NO_CHANGED_REVERSE_ARRAY_MSG);
}


int
main (const int argc, const char *argv[])
{
    // keep value of status
    int status;

    puts("\tExample reverse of an integer array");
    int arr_int[5] = {1, 2, 3, 4, 5};

    status = 0;
    PRINT_ARRAY(arr_int, 5, "%d");
    REVERSE_ARRAY(arr_int, -1, &status);

    // will be an error, since a length is less 0, and the array is not changed
    print_msg_reverse_array_status(status);
    PRINT_ARRAY(arr_int, 5, "%d");

    status = 0;
    REVERSE_ARRAY(arr_int, 0, &status);

    // a length is equal to 0, so an array is not changed
    print_msg_reverse_array_status(status);
    PRINT_ARRAY(arr_int, 5, "%d");

    status = 0;
    REVERSE_ARRAY(arr_int, 5, &status);
    print_msg_reverse_array_status(status);
    PRINT_ARRAY(arr_int, 5, "%d");

    puts("\n\tExample reverse of an float array");
    float arr_float[5] = {0.78, 2.1, -3.1, 4, 5.012};

    status = 0;
    PRINT_ARRAY(arr_float, 5, "%5.3f");
    REVERSE_ARRAY(arr_float, 5, &status);
    print_msg_reverse_array_status(status);
    PRINT_ARRAY(arr_float, 5, "%5.3f");

    puts("\n\tExample reverse of an double array");
    double arr_double[5] = {0.00001, 20000.002, -3, 4, 5.29999999};

    status = 0;
    PRINT_ARRAY(arr_double, 5, "%8.5f");
    REVERSE_ARRAY(arr_double, 5, &status);
    print_msg_reverse_array_status(status);
    PRINT_ARRAY(arr_double, 5, "%8.5f");
    return 0;
}

我使用GCC进行编译,结果必须是下一个

    Example reverse of an integer array
[1, 2, 3, 4, 5]
Status: Failed reverse for an array
[1, 2, 3, 4, 5]
Status: An array no changed
[1, 2, 3, 4, 5]
Status: An array succefully reversed
[5, 4, 3, 2, 1]

    Example reverse of an float array
[0.780, 2.100, -3.100, 4.000, 5.012]
Status: An array succefully reversed
[5.012, 4.000, -3.100, 2.100, 0.780]

    Example reverse of an double array
[ 0.00001, 20000.00200, -3.00000,  4.00000,  5.30000]
Status: An array succefully reversed
[ 5.30000,  4.00000, -3.00000, 20000.00000,  0.00000]

测试环境

$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 8.6 (jessie)
Release:    8.6
Codename:   jessie
$ uname -a
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux
$ gcc --version
gcc (Debian 4.9.2-10) 4.9.2

答案 7 :(得分:0)

你可以反转一个你不需要辅助数组的数组,这是我的C代码

#include <stdio.h>
int main(void)
 {
    int arr[5]={1,2,3,4,5};
    int size=sizeof(arr)/sizeof(int);   
    int success= reverse(arr,size);
    if(success==1)
        printf("Array reversed properly");
    else
        printf("Array reversing failed");   

    return 0;
}


int reverse(int arr[], int size)
{
    int temp=0;
    int i=0;
    if(size==0)
        return 0;
    if(size==1)
        return 1;

    int size1=size-1;
    for( i=0;i<(size/2);i++)
    {
        temp=arr[i];
        arr[i]=arr[size1-i];
        arr[size1-i]=temp;
    }

    printf("Numbers after reversal are ");
    for(i=0;i<size;i++)
    {
        printf("%d ",arr[i]);
    }
    return 1;

}

答案 8 :(得分:0)

#include<stdio.h>
void main() {
    int array[] = {0,1,2,3,4,5,6,7,8,9,10,12,13};
    int i,j;
    unsigned long int len = sizeof(array)/sizeof(array[i]);
    for(i=0; i<len/2; i++) {
        j = array[i];
        array[i] = array[(len-1)-i];
        array[(len-1)-i] = j;
    }
    for(i=0; i<len; i++) printf("%d ",array[i]);
    printf("\n");
}

答案 9 :(得分:0)

这是一个简单易用的函数,用于翻转各种大小的数组。根据您的数组类型更改参数:

void flipArray(int *a, int asize){
            int b[asize];
            int *b_p = b;

            for(int i=0; i<asize; i++){
                    //backwardsOrientation = (arraySize-1)-increment
                    b_p[asize-1-i] = a[i];
            }
            for(int i=0; i<asize; i++){
                    a[i] = b_p[i];
            }
    }

答案 10 :(得分:0)

 public static void ReverseArrayInPlace()
    {
        int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
        int end = arr.Length - 1;
        foreach (var item in arr)
        {
            Console.WriteLine(item);
        }

        for (int i = 0; i < arr.Length/2; i++)
        {
            var temp = arr[i];
            arr[i] = arr[end];
            arr[end] = temp;
            end--;
        }
        Console.WriteLine("--------------------------");

        foreach (var item in arr)
        {
            Console.WriteLine(item);
        }
    }

答案 11 :(得分:-1)

#include<Stdio.h>
#include<string.h>
#define max 25
int main()
{ 
  char arr[max]="0123456789";
  strrev(arr);
  atoi(arr);

  return 0;
}
//you can also use built in functions such as strrev(); string reverse atoi just 
//changes string into integer