Skip to content

Commit

Permalink
Rotate array
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Ma <begeekmyfriend@gmail.com>
  • Loading branch information
begeekmyfriend committed Nov 24, 2017
1 parent bede715 commit 55ba51b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 189_rotate_array/Makefile
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test rotate_array.c
49 changes: 49 additions & 0 deletions 189_rotate_array/rotate_array.c
@@ -0,0 +1,49 @@
#include <stdio.h>
#include <stdlib.h>

static void reverse(int *nums, int lo, int hi)
{
while (lo < hi) {
int tmp = nums[lo];
nums[lo] = nums[hi];
nums[hi] = tmp;
lo++;
hi--;
}
}

static void rotate(int* nums, int numsSize, int k)
{
k %= numsSize;
if (k == 0) {
return;
}

reverse(nums, 0, numsSize - 1 - k);
reverse(nums, numsSize - k, numsSize - 1);
reverse(nums, 0, numsSize - 1);
}

int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: ./test k n1 n2...\n");
exit(-1);
}

int k = atoi(argv[1]);
int i, count = argc - 2;
int *nums = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
nums[i] = atoi(argv[i + 2]);
}

rotate(nums, count, k);

for (i = 0; i < count; i++) {
printf("%d ", nums[i]);
}
printf("\n");

return 0;
}

0 comments on commit 55ba51b

Please sign in to comment.