Created
April 2, 2015 12:22
-
-
Save lotabout/b90215a99b2d6973d90b to your computer and use it in GitHub Desktop.
print sequence in order.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
#include <string.h> | |
void print_seq(int seq[], int len) | |
{ | |
int *indices = (int *)malloc(sizeof(int) * (len+1)); | |
memset(indices, 0, sizeof(int)*(len+1)); | |
int i; | |
for (i = 0; i <= len; ++i) { | |
indices[seq[i]] = i; | |
} | |
int prev_index = 0; | |
/* output the first item */ | |
for (i = 1; i <= len; ++i) { | |
if (indices[i] != 0) { | |
prev_index = indices[i]; | |
printf("%d", i); | |
break; | |
} | |
} | |
/* output the rest */ | |
for (i++; i <= len; i++) { | |
if (indices[i] < prev_index) { | |
printf(", %d", i); | |
} else { | |
/* new sequence */ | |
prev_index = indices[i]; | |
printf("\n%d", i); | |
} | |
} | |
printf("\n"); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int test[] = {1, 2, 5, 8, 10, 4, 3, 6, 9, 7}; | |
int len = sizeof(test)/sizeof(test[0]); | |
print_seq(test, len); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment