Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C sắp xếp tên theo thứ tự bảng chữ cái dùng struct

Sử dụng struct để lưu tên và số báo danh, sau đó sắp xếp theo tên (alphabetical) dùng strcmp và hoán đổi toàn bộ struct.

Chương trình

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

struct tag { char name[10]; int rno; };
typedef struct tag node;
node s[5];

void sort(int no) {
    int i, j; node temp;
    for (i = 0; i < no-1; i++)
        for (j = i+1; j < no; j++)
            if (strcmp(s[i].name, s[j].name) > 0) {
                temp = s[i]; s[i] = s[j]; s[j] = temp;
            }
}

void main() {
    int no, i;
    fflush(stdin);
    printf("Enter Number of Students: "); scanf("%d", &no);
    for (i = 0; i < no; i++) {
        printf("Enter Name: "); fflush(stdin); gets(s[i].name);
        printf("Enter Roll: "); scanf("%d", &s[i].rno);
    }
    sort(no);
    for (i = 0; i < no; i++)
        printf("%s\t%d\n", s[i].name, s[i].rno);
}

Kết quả

Enter 5 students: Priya(3), Hari(5), Pinky(7), Lucky(1), Krishna(2)
Sorted:
Hari    5
Krishna 2
Lucky   1
Pinky   7
Priya   3