Sort and Search Structure - C Data Structure

C examples for Data Structure:Sort

Description

Sort and Search Structure

Demo Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MaxStudents 100//  ww w  .j  ava 2  s. co m
#define MaxNameLength 30
#define MaxNameBuffer MaxNameLength+1

typedef struct {
    char name[MaxNameBuffer];
    int age;
    char gender;
} Student;

void getString(FILE *, char[]);
int getData(FILE *, Student[]);
int search(char[], Student[], int);
void sort(Student[], int);
void printStudent(Student);
void getString(FILE *, char[]);
    
int main() {
    Student student[MaxStudents];

    char aName[MaxNameBuffer];

    FILE * in = fopen("input.txt", "r");
    if (in == NULL) {
        printf("Error opening file: %s.\n", strerror(errno));
        exit(1);
    }

    int numStudents = getData(in, student);
    
    if (numStudents == 0) {
        printf("No data supplied for students");
        exit(1);
    }

    for (int i = 0; i < numStudents; i++) 
      printStudent(student[i]);

    getString(in, aName);
    
    while (strcmp(aName, "END") != 0) {
        int ans = search(aName, student, numStudents);
        if (ans == -1) 
           printf("%s not found\n", aName);
        else 
           printf("%s found at location %d\n", aName, ans);
        getString(in, aName);
    }

    sort(student, numStudents);
    
    for (int i = 0; i < numStudents; i++) 
       printStudent(student[i]);
}

void printStudent(Student t) {
    printf("Name: %s Age: %d Gender: %c\n", t.name, t.age, t.gender);
}
int getData(FILE *in, Student list[]) {
    char temp[MaxNameBuffer];
    
    char readChar(FILE *);

    int n = 0;
    getString(in, temp);
    while (n < MaxStudents && strcmp(temp, "END") != 0) {
        strcpy(list[n].name, temp);
        fscanf(in, "%d", &list[n].age);
        list[n].gender = readChar(in);
        n++;
        getString(in, temp);
    }
    return n;
}

int search(char key[], Student list[], int n) {
    for (int i = 0; i < n; i++)
        if (strcmp(key, list[i].name) == 0) return i;
    return -1;
}

void sort(Student list[], int n) {
    for (int i = 1; i < n; i++) {
        Student temp = list[i];
        int k = i - 1;
        while (k >= 0 && strcmp(temp.name, list[k].name) < 0) {
            list[k + 1] = list[k];
            k = k - 1;
        }
    list[k + 1] = temp;
    }
}

void getString(FILE * in, char str[]) {
    char ch, delim;
    int n = 0;
    str[0] = '\0';

    while (isspace(ch = getc(in))) ; //empty while body
    
    if (ch == EOF) 
       return;

    delim = ch;
    while (((ch = getc(in)) != delim) && (ch != EOF))
        str[n++] = ch;
    str[n] = '\0';
}

char readChar(FILE * in) {
    char ch;
    while (isspace(ch = getc(in))) ; //empty while body
    return ch;
}

Related Tutorials