-
Notifications
You must be signed in to change notification settings - Fork 0
/
csort.c
99 lines (81 loc) · 1.98 KB
/
csort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int split(char *s, char ***w)
{
char **words = NULL, *word = NULL, c = 1;
unsigned long wordscount = 0, charscount = 0;
while(c != '\0')
{
c = *(s++);
if(c != ' ' && c != '\0')
{
if(charscount == 0) word = (char *)malloc(sizeof(char));
else word = (char *)realloc(word, sizeof(char) * (charscount + 1));
*(word + charscount) = c;
charscount++;
}
else if(charscount != 0)
{
word = (char *)realloc(word, sizeof(char) * (charscount + 1));
word[charscount] = '\0';
charscount = 0;
words = (char **)realloc(words, sizeof(char *) * (wordscount + 1));
*(words + wordscount) = word;
wordscount++;
}
}
*w = words;
return wordscount;
}
void csort(char *src, char *dest)
{
char **words;
int wcount = split(src, &words), null_term_idx = 0;
int count[wcount];
for(int i = 0; i < wcount; i++) count[i] = 0;
for(int i = 0; i < wcount - 1; i++)
{
int l1 = strlen(words[i]);
null_term_idx += l1 + 1;
for(int j = i + 1; j < wcount; j++)
{
int l2 = strlen(words[j]);
if(l1 > l2) count[i] += l2 + 1;
else count[j] += l1 + 1;
}
}
null_term_idx += strlen(words[wcount-1]);
for(int i = 0; i < wcount; i++)
strcpy(dest + count[i], words[i]);
for(int i = 0; i < wcount; i++)
if(count[i] != 0) dest[count[i] - 1] = ' ';
dest[null_term_idx] = '\0';
for(int i = 0; i < wcount; i++)
free(words[i]);
free(words);
}
int get_string(char **p)
{
char *words = (char*)malloc(sizeof(char)), c;
scanf("%c", &c);
int slen = 0, tr_slen = -1;
while(c != '\n')
{
words[slen] = c;
words = (char*)realloc(words, sizeof(char) * (++slen + 1));
scanf("%c", &c);
}
words[slen] = '\0';
*p = words;
return slen;
}
int main(){
char *string, c;
int slen = get_string(&string);
char sorted_string[slen];
csort(string, sorted_string);
printf("%s\n", sorted_string);
free(string);
return 0;
}