Skip to content

Instantly share code, notes, and snippets.

@AmirHosein-Gharaati
Last active May 13, 2023 19:17
Show Gist options
  • Save AmirHosein-Gharaati/5de7525f0886b205d4126f7008757a66 to your computer and use it in GitHub Desktop.
Save AmirHosein-Gharaati/5de7525f0886b205d4126f7008757a66 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000000
char* get_str();
void sort(char**, int);
int main() {
// input: amirhosein amir alireza mohsen mohammad
int n = 5;
char **strings = malloc(n * sizeof(char*));
for(int i =0; i < n; i++) {
strings[i] = get_str();
}
sort(strings, n);
for(int i =0; i < n; i++) {
printf("%s\n", strings[i]);
}
for(int i =0; i < n; i++)
free(strings[i]);
free(strings);
return 0;
}
void swap(char **a, char **b) {
char *temp = *a;
*a = *b;
*b = temp;
}
int is_whitespace(char ch) {
if(ch == ' ' || ch == '\t' || ch == '\n')
return 1;
return 0;
}
void my_strcpy(char *a, char *b){
while((*a++ = *b++));
}
int my_strlen(const char *a) {
int n;
for(n = 0; a[n] ;n++);
return n;
}
char* get_str(){
char *ptr = malloc(MAX* sizeof(char));
char c;
while(is_whitespace(c = getchar()));
if(c == EOF) {
free(ptr);
return NULL;
}
int i;
for(i = 0; !is_whitespace(c) && c != EOF; c = getchar(), i++) {
ptr[i]=c;
}
ptr[i] = '\0';
int len = my_strlen(ptr);
char *str = malloc((len+1) * sizeof(char));
my_strcpy(str, ptr);
free(ptr);
return str;
}
void sort(char **strings, int n){
for(int i = 0 ; i < n; i++) {
for(int j = 0; j < n-1; j++) {
if(my_strlen(strings[j]) > my_strlen(strings[j+1])) {
swap(&strings[j], &strings[j+1]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment