Wednesday, April 17, 2013

Sort structure type using insertion sort method

In this case,the input is sorted while reading and placing it in the array.In all other methods,all input values are placed in array before applying the actual sorting procedure.But here ,the values are sorted while reading them from console.Here the student details are accepted as input and stored in structure type array.Then it is sorted as per the value of the percentage.
Basic steps are as follows -
-Read a value form console.
-In order to place it in given array find its position in such a way that after its insertion the resultant data must be in sorted order.
-For this purpose,start shifting the values from bottom of the array downward by one position till getting a proper position.
-Insert a new value after getting its proper position.


//... C Language Program to sort the Student Records by using an Insertion Sort method

# include < stdio.h >
# include < conio.h >

struct stud
{
    int roll;
    char name[15];
    float per;
};

void main()
{
    struct stud a[50], t;
    int n;

    clrscr();

    printf("\n C Language Program to sort the Student Records by using Insertion Sort method ");
    printf("\n To sort the Student Records in Dercreasing Order of % (Percentage) \n");

    printf("\n Enter How Many Records [ i.e. Size of Array (n) ] : ");
    scanf("%d", &n);

    insrtn_srt(a, n);

    printf("\n %d Values After Sorting are \n", n);
    print_data(a, n);

} // main

int print_data( struct stud a[], int n )
{
    int i;

    printf("\n Roll No. \t Name \t Percentage (%) \n");
    for(i = n - 1; i >= 0; i--)
            printf("\n \t %d \t %s \t %0.2f", a[i].roll, a[i].name, a[i].per);
    return;
} // print_data

int insrtn_srt( struct stud a[], int n )
{
    int i, j, bottom;
    struct stud t;

    bottom = -1;
    for(j = 0; j < n; j++)
    {
        printf("\n Roll Number : ");
        scanf("%d", &t.roll);
        printf("\n Name : ");
        flushall();
        scanf("%s", t.name);
        printf("\n Percentage (%) : ");
        scanf("%f", &t.per);
        i = bottom;
        while( a[i].per > t.per && i != -1)
        {
            a[i+1] = a[i];
            i--;
        } // while
        a[i+1] = t;
        bottom++;
    } // for
    return;
} // insrtn_srt

No comments:

Post a Comment