Advertisement
Guest User

Untitled

a guest
Oct 16th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. /*Write a program that reads string from the standard input. All strings will contain no 0-byte characters and will be terminated by a \n newline. The last line of input might not be terminated by a newline character. After reading all strings, these strings should be sorted according of the order of the strcmp function as provided by libc. After all strings have been sorted, these string should be printed to STDOUT in the new order. Every string should be terminated by a \n newline character when writing it to STDOUT.
  2.  
  3. In this task, there will be at most 20 strings in the input, each one of them at most 20 characters long including the terminating \n newline.
  4.  
  5. Your solution must be saved in sort.c. You are not allowed to add additional files or change the Makefile.
  6.  
  7. There is a test in test.sh, that checks your compiled code against a few test cases. Feel free to add more tests. When the tests are passed with success, then test.sh will print "OK". */
  8.  
  9.  
  10.  
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14.  
  15. int main(int argc, char ** argv) {
  16. int maxLen = 20;
  17. char str[maxLen][maxLen];
  18.  
  19. int i = 0, count = 0;
  20.  
  21. while (i < maxLen && fgets(str[i], maxLen, stdin) != NULL) {
  22. int strLength = strlen(str[i]);
  23. if(str[i][strLength - 1] == '\n' && strLength > 0) {
  24. str[i][strLength - 1] = '\0';
  25. }
  26. count++;
  27. }
  28.  
  29. char key[maxLen];
  30.  
  31. int j = 0;
  32.  
  33. for (i = 1; i < count; i++) {
  34. strncpy(key, str[i], maxLen);
  35. j = i-1;
  36.  
  37. /* Move elements of arr[0..i-1], that are
  38. greater than key, to one position ahead
  39. of their current position */
  40. while (j >= 0 && strncmp(str[i], key, maxLen) > 0) {
  41. strncpy(str[j+1], str[j], maxLen);
  42. j = j-1;
  43. }
  44. strncpy(str[j+1], key, maxLen);
  45. }
  46.  
  47. for (i = 0; i < count; i++) {
  48. printf("%s\n", str[i]);
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement