This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
sys_prog/sortstrings/sortstrings.c

48 lines
1 KiB
C
Raw Normal View History

2019-10-11 07:29:40 +00:00
const unsigned int MAX_N = 1000;
2019-10-09 08:18:40 +00:00
2019-10-11 07:29:40 +00:00
unsigned int c_strlen(const char* s) {
unsigned int i = 0;
for (; *s; s++) i++;
return i;
2019-10-09 08:18:40 +00:00
}
2019-10-11 07:29:40 +00:00
unsigned int less_than(const char *s1, const char* s2) {
for(; *s1 == *s2 && *s1; s1++) s2++;
return (*s1 < *s2);
}
void insertion_sort(const char* strs[], unsigned int n) {
for (unsigned int i = 0; i < n-1; i++) {
for (unsigned int j = i+1; j > 0; j--) {
if (less_than(strs[j], strs[j-1])) {
const char* tmp = strs[j-1];
strs[j-1] = strs[j];
strs[j] = tmp;
} else {
break;
}
}
}
}
void sort_strings(const char* input, char* output, unsigned int n) {
2019-10-09 08:18:40 +00:00
const char* strings[MAX_N];
2019-10-11 07:29:40 +00:00
unsigned int i = 0;
unsigned int offset = 0;
2019-10-09 08:18:40 +00:00
for (i = 0; i < n; i++) {
strings[i] = input + offset;
2019-10-11 07:29:40 +00:00
offset += c_strlen(input + offset) + 1; // + 1 for NUL
2019-10-09 08:18:40 +00:00
}
2019-10-11 07:29:40 +00:00
insertion_sort(strings, n);
2019-10-09 08:18:40 +00:00
offset = 0;
for (i = 0; i < n; i++) {
2019-10-11 07:29:40 +00:00
const unsigned int len = c_strlen(strings[i]);
for (unsigned int j = 0; j <= len; j++) {
output[offset + j] = strings[i][j];
}
2019-10-09 08:18:40 +00:00
offset += len + 1;
}
}