Один метод с использованием qsort (проверено):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Changeable constants
const size_t MAX_LENGTH = 100;
const size_t N_NAMES = 10;
//Simple alias for lazy ones
typedef char String[MAX_LENGTH];
//fgets keeps the \n at the end of the
//returned string : this function removes it
void remove_end_rc(char * const string) {
size_t const len = strlen(string);
if(len && string[len-1] == '\n')
string[len-1] = '\0';
}
//Input function
void ask_names(String names[N_NAMES]) {
for(size_t i = 0 ; i < N_NAMES ; ++i) {
printf("Name %u ? ", i+1);
fgets(names[i], MAX_LENGTH, stdin);
remove_end_rc(names[i]);
}
}
//Output function
void print_names(String const names[N_NAMES]) {
printf("Sorted :\n");
for(size_t i = 0 ; i < N_NAMES ; ++i) {
printf("%u) %s\n", i+1, names[i]);
}
}
int alpha_cmp(void const *str1, void const *str2 ) {
return strcmp((char const*)str1,(char const*)str2);
}
int main(void) {
String names[N_NAMES] = {""};
ask_names(names);
//Sort alphabetically using strcmp
qsort(names, N_NAMES, MAX_LENGTH, alpha_cmp);
print_names(names);
return 0;
}
Другой метод без qsort (), использующий пузырьковый алгоритм:
#include <stdio.h>
#include <string.h>
/** Types *************************************/
//Changeable constants
#define MAX_LENGTH 100
#define N_NAMES 10
//Simple aliases for lazy ones
typedef char String[MAX_LENGTH];
typedef String Names[N_NAMES];
/** Input/Output ******************************/
//fgets keeps the \n at the end of the
//returned string : this function removes it
void remove_end_rc(char * const string) {
size_t const len = strlen(string);
if(len && string[len-1] == '\n')
string[len-1] = '\0';
}
//Input function
void ask_names(Names names) {
for(size_t i = 0 ; i < N_NAMES ; ++i) {
printf("Name %u ? ", i+1);
fgets(names[i], MAX_LENGTH, stdin);
remove_end_rc(names[i]);
}
}
//Output function
void print_names(Names names) {
printf("Sorted :\n");
for(size_t i = 0 ; i < N_NAMES ; ++i) {
printf("%u) %s\n", i+1, names[i]);
}
}
/** Sorting *************************************/
//Explicit
void swap_str(String s1, String s2) {
String temp = "";
strcpy(temp, s1);
strcpy(s1, s2);
strcpy(s2, temp);
}
#include <stdbool.h>
//Sorts alphabetically using bubble algorithm
void alpha_sort(Names names)
{
bool swapped;
do {
swapped = false;
for(size_t i = 0 ; i < N_NAMES-1 ; ++i) {
if(strcmp(names[i], names[i+1])) {
swap_str(names[i], names[i+1]);
swapped = true;
}
}
}while(!swapped);
}
/** Main program **********************************/
int main(void) {
Names names = {""};
ask_names(names);
alpha_sort(names);
print_names(names);
return 0;
}
Вы можете улучшить его, позаботившись о падежах (нижний, верхний), символах ... Но в основном это делает свое дело.