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.0 KiB
C

const unsigned int MAX_N = 1000;
unsigned int c_strlen(const char* s) {
unsigned int i = 0;
for (; *s; s++) i++;
return i;
}
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) {
const char* strings[MAX_N];
unsigned int i = 0;
unsigned int offset = 0;
for (i = 0; i < n; i++) {
strings[i] = input + offset;
offset += c_strlen(input + offset) + 1; // + 1 for NUL
}
insertion_sort(strings, n);
offset = 0;
for (i = 0; i < n; i++) {
const unsigned int len = c_strlen(strings[i]);
for (unsigned int j = 0; j <= len; j++) {
output[offset + j] = strings[i][j];
}
offset += len + 1;
}
}