Skip to content

Commit

Permalink
Sort colors
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Ma <[email protected]>
  • Loading branch information
begeekmyfriend committed Aug 26, 2017
1 parent e698e78 commit 0f3b43b
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 075_sort_colors/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test sort_colors.c
57 changes: 57 additions & 0 deletions 075_sort_colors/sort_colors.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}

/*
* RED = 0
* WHITE = 1
* BLUE = 2
*/
static void sortColors(int* nums, int numsSize) {
int i = 0, j = numsSize - 1;
while (i < j) {
while (nums[i] == 0 && i < j) {
i++;
}
while (nums[j] != 0 && j > i) {
j--;
}
swap(nums + i, nums + j);
}
j = numsSize - 1;
while (i < j) {
while (nums[i] == 1 && i < j) {
i++;
}
while (nums[j] != 1 && j > i) {
j--;
}
swap(nums + i, nums + j);
}
}

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: ./test colors\n");
exit(-1);
}
int i, count = strlen(argv[1]);
int *nums = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
nums[i] = argv[1][i] - '0';
}
sortColors(nums, count);
for (i = 0; i < count; i++) {
printf("%d", nums[i]);
}
printf("\n");
return 0;
}

0 comments on commit 0f3b43b

Please sign in to comment.