stringsort.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. idee, een programma dat een lijst van strings krijgt, en ze dan sorteert op
  3. alphabetische volgorde, idealiter ook met hele nummbers if relevant (dus niet
  4. alleen individuele digits)
  5. split into strings and numbers
  6. okay dit werkt nu omzetten naar strings
  7. */
  8. #include <stddef.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <time.h>
  13. #define WORDS 16
  14. #define WORDLENGTH 64
  15. /* return 1 if word1 < word 2*/
  16. int compareword(char word1[], char word2[]) {
  17. for (int i = 0; i < WORDLENGTH; i++) {
  18. if (word1[i] == word2[i]) {
  19. //it should continue
  20. }
  21. else if (word1[i] < word2[i]) {
  22. printf("%s is larger than %s\n", word1, word2);
  23. return 1;
  24. }
  25. else {
  26. return 0;
  27. }
  28. }
  29. return 0;
  30. }
  31. /* eerst gewone bubblesort weer doen */
  32. int mybubblesort(char inputarr[WORDS][WORDLENGTH]) {
  33. for (int i = 0; i < WORDS - 1; i++) { // voor elk woord
  34. for (int j = 0; j < WORDS - 1; j++) { // ga langs elk woord
  35. if (compareword(inputarr[j], inputarr[j + 1])) { // als huidig nummer groter is
  36. // swap hem dan
  37. char temp[64];
  38. strcpy(temp, inputarr[j+1]);
  39. strcpy(inputarr[j+1], inputarr[j]);
  40. strcpy(inputarr[j], temp);
  41. }
  42. }
  43. }
  44. for (int i = 0; i < WORDS - 1; i++) {
  45. if (inputarr[i][0] > 0) {
  46. printf("num:%i, %s\n", i, inputarr[i]);
  47. }
  48. //puts(inputarr[i]);
  49. }
  50. return 0;
  51. }
  52. int main() {
  53. char mytest[16][64] = {"pear", "watermelon", "aap", "apple", "banana", "cantaloupe", "Elephant", "Zebra"};
  54. srand(time(NULL));
  55. mybubblesort(mytest);
  56. return 0;
  57. }