C程序 - 在数组中移动元素

时间:2016-02-05 21:28:56

标签: c arrays

“编写一个程序,允许用户输入一个数组大小的整数。建议使用Malloc。随机为数组的每个元素生成一个整数。接下来,创建一个旋转数组的函数。数组意味着每个元素向右或向左移动一个索引,并且数组的最后一个元素也移动到第一个位置“

示例:31 83 91

要转移的方向和次数? - 左

您想转移多少次? 2

最终结果:91 31 83

目前我的代码。它并没有改变。

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

int main(){

int i, temp, swapped;
int SlotNumber;
int *ptr;
char direction;
int ShiftAmount;

printf("How many slots would you like in your array?\n");
scanf("%d", &SlotNumber);
for(i=0;i<SlotNumber;i++){
    printf("%d \t", rand());
}
ptr = (int *)malloc(SlotNumber*sizeof(int));

printf("\nWhich direction would you like to shift it to? R/L?\n");
scanf(" %c", &direction);
printf("\nHow many times would you like to shift?\n");
scanf("%d", &ShiftAmount);

if((direction=='R')||(direction=='r')){
    while(1){
        swapped = 0;
        for(i=0;i<ptr+1;i++){
            if(ptr[1]>ptr[i+ShiftAmount]){
                int temp = ptr[i];
                ptr[i] = ptr[i+ShiftAmount];
                ptr[i+ShiftAmount] =temp;
                swapped = 1;
            }
        }
        if(swapped == 0);
        break;
    }
}
printf("\nNewList\n");
for(i=0;i<ptr;i++){
    printf("%d \t",ptr[i]);
}

return 0;
}

1 个答案:

答案 0 :(得分:1)

您的代码几乎没有问题。这是左移的改进解决方案,右移我留给你。

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


int main()
{

    int i, j;
    int SlotNumber;
    int *ptr;
    int ShiftAmount;
    int temp;

    srand(time(NULL));

    printf("How many slots would you like in your array?\n");
    scanf("%d", &SlotNumber);

    ptr = malloc(SlotNumber*sizeof(int));

    // Fill array with random numbers
    for(i=0;i < SlotNumber; i++)
    {
        ptr[i]=rand();
        printf("%d \t",ptr[i]);

    }

    printf("\nHow many times would you like to shift?\n");
    scanf("%d", &ShiftAmount);


    for(i=0; i < ShiftAmount; i++)
    {
        temp = ptr[0];
        for(j=0;j < SlotNumber - 1;j++)
        {
            ptr[j] = ptr[j+1];
        }
        ptr[SlotNumber - 1]=temp;
    }

    printf("\nNewList\n");
    for(i=0; i < SlotNumber; i++)
    {
        printf("%d \t",ptr[i]);
    }

    free(ptr);

    return 0;
}