Skip to content

Commit

Permalink
Next permutation
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Jul 20, 2017
1 parent 82cb9ab commit ab9a9bd
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 031_next_permutation/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test next_permutation.c
63 changes: 63 additions & 0 deletions 031_next_permutation/next_permutation.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#include <stdio.h>
#include <stdlib.h>

static void reverse(int *a, int size)
{
int left = 0;
int right = size - 1;
while (left < right) {
int tmp = a[left];
a[left] = a[right];
a[right] = tmp;
left++;
right--;
}
}

void nextPermutation(int* nums, int numsSize) {
if (numsSize <= 1) {
return;
}

int *p = nums + numsSize - 1;
int *q = nums + numsSize - 1;

while (p != nums && *(p - 1) >= *p) {
p--;
}

if (p != nums) {
int n = *(p - 1);
while (*q <= n) {
q--;
}

int tmp = *q;
*q = *(p - 1);
*(p - 1) = tmp;
}
reverse(p, numsSize - (p - nums));
}

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

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

nextPermutation(nums, argc - 1);

for (i = 0; i < argc - 1; i++) {
printf("%d", nums[i]);
}
putchar('\n');

return 0;
}

0 comments on commit ab9a9bd

Please sign in to comment.