Last active
August 30, 2024 19:30
-
-
Save JustLinuxUser/d5640659954cc2f20be4a834a3868595 to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
#include <string.h> | |
void ft_advanced_sort_string_tab(char **tab, int (*cmp)(const char *, const char *)) | |
{ | |
int i; | |
int j; | |
char *temp; | |
i = 0; | |
while (tab[i] != 0 && tab[i + 1] != 0) | |
{ | |
j = i + 1; | |
while (tab[j] != 0) | |
{ | |
if (cmp(tab[i], tab[j]) > 0) | |
{ | |
temp = tab[i]; | |
tab[i] = tab[j]; | |
tab[j] = temp; | |
} | |
j++; | |
} | |
i++; | |
} | |
} | |
int is_sorted(char **tab, int (*cmp)(const char *, const char *)) { | |
for (int i = 0; tab[i] && tab[i + 1]; i++) { | |
if (cmp(tab[i], tab[i + 1]) > 0) | |
return (0); | |
} | |
return (1); | |
} | |
char *gen_random_string() { | |
int size = rand() % 100; | |
char *str = malloc(size + 1); | |
for (int i = 0; i < size; i++) { | |
char c = rand() % ('~' - '!') + '!'; | |
str[i] = c; | |
} | |
str[size] = 0; | |
return (str); | |
} | |
char **gen_random_tab() { | |
int size = rand() % 100; | |
char **tab = malloc(sizeof(char *) * (size + 1)); | |
tab[size] = 0; | |
for (int i = 0; i < size; i++) { | |
tab[i] = gen_random_string(); | |
} | |
return (tab); | |
} | |
void free_tab(char ***tab) { | |
for (int i = 0; (*tab)[i]; i++) { | |
free((*tab)[i]); | |
} | |
free(*tab); | |
*tab = 0; | |
} | |
void print_tab(char **tab) { | |
printf("\n"); | |
for (int i = 0; tab[i]; i++) { | |
printf("%s\n", tab[i]); | |
} | |
} | |
int main() { | |
for (int i = 0; i < 100000; i++) { | |
char **tab = gen_random_tab(); | |
ft_advanced_sort_string_tab(tab, strcmp); | |
if (!is_sorted(tab, strcmp)) | |
return (1); | |
free_tab(&tab); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment