SORT NAMES IN ALPHABETICAL ORDER USING POINTERS
SORT NAMES IN ALPHABETICAL ORDER USING POINTERS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 5
#define MAX_STRLEN 256
#define MAX_NAMELEN 128
typedef struct {
char *first;
char *last;
} Name;
void sort(Name *a, int n);
Name *nameArray;
int main(int argc, char *argv[]) {
int i;
char line[MAX_STRLEN],*p;
nameArray = (Name *)calloc(N,sizeof(Name));
printf("\nEnter %d names (First Last), one per line:\n",N);
for (i = 0; i < N; i++) {
printf("> ");
fgets(line,MAX_STRLEN,stdin);
*(strchr(line,'\n')) = '\0';
if (strlen(line) > 0) {
/*
* Could use some more logic here to verify input.
* This will work for : First Last
*/
p = strchr(line,' '); *p++ = '\0';
nameArray[i].first = (char *)malloc(strlen(line));
nameArray[i].last = (char *)malloc(strlen(p));
strcpy(nameArray[i].first,line);
strcpy(nameArray[i].last,p);
}
}
sort(nameArray,N);
printf("\nSorted:\n");
for (i = 0; i < N; i++) {
printf("%s, %s\n",
nameArray[i].last, nameArray[i].first);
free(nameArray[i].first);
free(nameArray[i].last);
}
free(nameArray);
return 0;
}
/* selection sort */
void sort(Name *a, int n) {
int min,i,j;
Name t;
for (i = 0; i < n; i++) {
min = i;
for (j = i+1; j < n; j++) {
if (strcmp(a[j].last,a[min].last) < 0) min = j;
}
t = a[min];
a[min] = a[i];
a[i] = t;
}
}
Comments
Post a Comment