I've been into algorithms lately, so I wanted to apply a simple algorithm using a language of my choice, which was C in this case.
I've implemented the bubblesort algorithm (for strings) in a simple program:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define NUM_NAMES (5)
void sort(char ** sorted, char ** strs, const size_t size, const bool ascending) { // using the bubble sort algorithm
sorted[0] = strs[0];
char ** f = strs;
for(int u=0; u < size; ++u) {
for(int i = 0; i < size - 1; ++i) {
if (strcmp(sorted[i], f[i+1]) <= 0) { // sorted[i] is first
sorted[i+1] = f[i+1];
} else { // f[i+1] is first
char *temp = f[i]; // just in case f == sorted, they'll point to the same thing ..
sorted[i] = f[i+1];
sorted[i+1] = temp;
}
}
f = sorted;
}
if (!ascending) { // reverse it !
char *reversed[size]; // temporarily
int i1 = 0, i2 = size - 1;
while (i1 < size && i2 >= 0) { // one condition would do. Only to be thread-safe
reversed[i1] = sorted[i2];
i1++;i2--;
}
for(int i = 0; i < size; ++i)
sorted[i] = reversed[i]; // putting it to sorted
}
}
void printNames(char * q, char ** names, int num) {
printf("\t%s\n", q);
for(int i = 0; i < num; ++i)
printf("%d: %s\n", i+1, names[i]);
for(int i = 0; i < 30; ++i)
printf("=");
printf("\n");
}
int main(int argc, char const *argv[])
{
char * names[] = {
"This should be Second",
"This should be First",
"This should be before the last",
"Wait .. That's the last!",
"This should be Third"
};
char *names_ordered[NUM_NAMES];
printNames("Original", names, NUM_NAMES);
sort(names_ordered, names, NUM_NAMES, true);
printNames("Ascending", names_ordered, NUM_NAMES);
sort(names_ordered, names, NUM_NAMES, false);
printNames("Descending", names_ordered, NUM_NAMES);
return 0;
}
I want to know if there's a problem with the sort function, especially in the reversing part, because I think that that's not efficient.