#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h> // for gettickcount, u could use time(NULL) aswell
#define MAX 99
#define LEN 21 //add 1 for trailing 0 char
int compare(const void *arg1, const void *arg2)
{
return stricmp((char*)arg1, (char*)arg2);
}
/* this getnames generates random chars and fills them
* into a 2-dimensional array; in order to read random
* inputted names from stdin u can modify it to your needs
* (i'll leave this for you as an easy exercice)
*/
void getnames(char names[][LEN], int num)
{
int i, j;
char arr[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for (i = 0; i < num; i++)
{
j = rand() % 20;
while (j >= 0)
{
names[i][j] = arr[rand() % 36];
j--;
}
}
}
void sort_names(char names[][LEN], int num, int type)
{
int i, j;
char temp[MAX][LEN] = {{0}, {0}};
/* this has been sorted from 0-Z
* qsort() is a sorting function
* that u can find in stdlib.h
*/
qsort((void*)names, (size_t)num, LEN, compare);
switch (type)
{
/* sort from last to first */
case 1:
for (i = 0; i < num; i++)
{
strcpy(&temp[i], &names[i]);
memset(&names[i], 0, LEN);
}
for (i = 0, j = num - 1; i < num; i++, j--)
strcpy(&names[i], &temp[j]);
break;
/* do nothing all is sorted already */
case 2:
break;
/* sorry but u weren't much clear with this option
* so u can implement the sort via age here
*/
case 3:
break;
}
}
void print_names(char names[][LEN], int num)
{
int i;
printf("\n");
for (i = 0; i < num; i++)
printf("%s\n", names[i]);
printf("\n");
}
int main(void)
{
int type, num;
char names[MAX][LEN] = {{0}, {0}};
srand(GetTickCount());
/* Ask user for how many names*/
printf("How many names?: ");
scanf("%d",&num);
if (num <= 0) exit(0);
if (num >= 100)
{
printf("Entered too many\n");
exit(0);
}
/*Get the names for the users*/
getnames(names, num);
/*Ask user how to sort names*/
printf("How to sort names?\n");
printf("1: Last\n2: First\n3: Age\n");
scanf("%d",&type);
/*Sort the names*/
sort_names(names, num, type);
/*Print the sorted array out*/
print_names(names, num);
system("PAUSE");
return 0;
}
i hope this will help u out ;)