对C中的结构元素进行排序并打印出来

时间:2018-09-25 23:46:10

标签: c sorting data-structures structure

我想以相同的方式将k_p从大到小降序,对10个学生的s_s_s进行排序并打印出来,但我不知道该怎么做...

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

struct student {
    float k_p;
    char i_p[30];
    int s_s_s;
};

int main() {
    struct student S[10];
    int i;
    for(i=0;i<10;i++) {
        printf("Student broj %d\n", i+1);
        printf("Koeficijent place: \t"); scanf("%d", &S[i].k_p);
        printf("Ime i prezime: \t"); scanf("%s", &S[i].i_p);
        printf("Stupanj strucne spreme: \t"); scanf("%f",&S[i].s_s_s);
        system("cls");
    }
    return 0;
}

我尝试了类似的方法,但是我不知道如何将其放入代码中

{
    for (int j = 0; j < n; j++) {     //Loop for comparing other values
        if (a[j] < a[i]) {            //Comparing other array elements
            int tmp = a[i];           //Using temporary variable for storing last value
            a[i] = a[j];              //replacing value
            a[j] = tmp;               //storing last value
        }
    }
}

2 个答案:

答案 0 :(得分:0)

一种方法:创建一个整数数组,它与结构体数组(数组S)具有相同的大小 ,并且初始化为从0到n -1 (其中n是大小)。

使用您认为合适的任何排序算法对该整数数组进行排序,并将数组A中的每个整数视为数组S的索引

通过根据k_p或s_s_s对索引数组进行排序,可以有效地打印数组S,就好像它是通过对k_p或s_s_s降序进行排序一样。

让我们使用冒泡排序(一种简单的排序算法来说明),我们将根据降序的k_p值进行排序:

    int A[] = {0,1,2,3,4,5,6,7,8,9};
    float k1,k2;
    // bubble sort for descending order
    for (int i = 0; i < n; i++) 
    {   
        k1 = &S[i].k_p;
        for (int j = 1; j < n; j++)             
        {
            k2 = &S[j].k_p;
            if (k1 < k2)               
            {
                // remember you're only switching the ints in array A
                int tmp = A[i];         
                A[i] = A[j];           
                A[j] = tmp;             
            }
        }
    }

**免责声明:我没有测试代码,但这是总体思路。

答案 1 :(得分:0)

如果要对整个结构进行排序,则需要使用适当的交换函数,该函数将交换两个结构元素而不是两个整数。

由于此结构包含一个整数,一个字符数组和一个浮点数,所以交换函数应注意交换所有三个元素。

/* in Global area */ 
float ftemp;
char chartemp[30];
int itemp;

void swap(struct student *a, struct student *b)
{

    /* swap the float */
    ftemp  = a->k_p;
    a->k_p = b->b_p;
    b->k_p = ftemp;

    /* swap the array */
    strcpy(chartemp, a->i_p);
    strcpy(a->i_p, b->i_p);
    strcpy(b->i_p, chartemp);

    /* swap the int */
    itemp    = a->s_s_s;
    a->s_s_s = b-> s_s_s;
    b->s_s_s = itemp;

}    

然后,您可以使用任何排序算法进行排序,例如冒泡排序,插入排序,合并排序调用上述函数以交换值。

注意-临时变量被放置在全局区域中,因为交换函数将被多次调用,这会在运行时间上带来很小的提升。如果您希望以这种方式对许多元素进行排序(超过100000),那么结构并不是实现它的理想方法。对此更好的是链接列表。在链接列表中,您只需要交换指针,而无需交换整个数据。