2017年6月6日 星期二

氣泡排序法(bubble sort)

student.dat
101 John   80
102 Bo 98
103 Mary 76
104 Bruce 87
105      Mark   32
106      Kevin  96
/*the filename: main
 *the filename extension: .c
 */
#include <stdio.h>
#include <stdlib.h>
#define SIZE 6
typedef struct data
{
    int num;
    char name[10];
    int score;
} d;

void print_data(d x[])
{
    int i;
    for(i=0; i<SIZE; i++)
        printf("%10d %10s %10d\n",x[i].num,x[i].name,x[i].score);
}

int main()
{
    FILE *f = fopen("student.dat","r");
    d data[SIZE];
    d temp;  //temporary storage space
    int i=0;
    while(fscanf(f,"%d %s %d",&data[i].num,data[i].name,&data[i].score)!=EOF)
        i++;
    fclose(f);
    print_data(data);
    int j;
    for (i = 0; i < SIZE-1; i++)
    {
        for (j = 0; j < (SIZE-1)-i; j++)
        {
            if (data[j].score > data[j+1].score)
            {
                //Adjacent two places for data exchange
                temp = data[j];
                data[j] = data[j+1];
                data[j+1] = temp;
            }
        }
    }
    printf("*******************************************\n");
    print_data(data);
    return 0;
}



沒有留言:

張貼留言