string sort using char [][]

This commit is contained in:
2026-05-30 01:40:22 +02:00
parent e0d044e719
commit 42c08d947f
+33 -28
View File
@@ -6,58 +6,63 @@ alleen individuele digits)
split into strings and numbers split into strings and numbers
okay dit werkt nu omzetten naar strings
*/ */
#include <stddef.h> #include <stddef.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <time.h> #include <time.h>
struct chickendynarr {
int *arr;
size_t length;
};
struct chickendynarr *createarr(int size) { #define WORDS 16
#define WORDLENGTH 64
struct chickendynarr *myarr = malloc(sizeof(int) * size); /* return 1 if word1 < word 2*/
myarr->length = size; int compareword(char word1[], char word2[]) {
myarr->arr = (int *)(myarr + 1); for (int i = 0; i < WORDLENGTH; i++) {
if (word1[i] < word2[i]) {
for (int i = 0; i < size - 1; i++) { printf("%s is larger than %s\n", word1, word2);
int randnumb = rand() % 20; return 1;
myarr->arr[i] = randnumb; }
printf("num%d:%d\n", i, randnumb); else {
return 0;
}
}
return 0;
} }
return myarr;
}
/* eerst gewone bubblesort weer doen */ /* eerst gewone bubblesort weer doen */
int mybubblesort(struct chickendynarr *inputarr) { int mybubblesort(char inputarr[WORDS][WORDLENGTH]) {
for (int i = 0; i < inputarr->length - 1; i++) { // voor elk nummer for (int i = 0; i < WORDS - 1; i++) { // voor elk woord
for (int j = 0; j < inputarr->length - 1; j++) { // ga langs elk nummer for (int j = 0; j < WORDS - 1; j++) { // ga langs elk woord
if (inputarr->arr[j] > if (compareword(inputarr[j], inputarr[j + 1])) { // als huidig nummer groter is
inputarr->arr[j + 1]) { // als huidig nummer groter is
// swap hem dan // swap hem dan
int temp = inputarr->arr[j]; char temp[64];
inputarr->arr[j] = inputarr->arr[j + 1]; strcpy(temp, inputarr[j+1]);
inputarr->arr[j + 1] = temp; strcpy(inputarr[j+1], inputarr[j]);
strcpy(inputarr[j], temp);
} }
} }
} }
for (int i = 0; i < inputarr->length - 1; i++) { for (int i = 0; i < WORDS - 1; i++) {
printf("num:%d, %d\n", i, inputarr->arr[i]); if (inputarr[i][0] > 0) {
printf("num:%i, %s\n", i, inputarr[i]);
}
//puts(inputarr[i]);
} }
return 0; return 0;
} }
int main() { int main() {
char mytest[16][64] = {"pear", "watermelon", "apple", "banana", "cantaloupe", "Elephant", "Zebra"};
srand(time(NULL)); srand(time(NULL));
struct chickendynarr *myarr = createarr(5); mybubblesort(mytest);
mybubblesort(myarr);
return 0; return 0;
} }