使用结构数组在C中实现排序算法的问题

0 c sorting bubble-sort

那么这是我的小问题,首先是我的代码:


struct alumn {
    char name[100];
    char lastname[100];
    int par;
    int nota;
};

typedef struct alumn alumn;

int bubble(alumn **arr, int length) { int i,j; alumn *temp;

for (i=0; i<=length-2; i++) {
    for (j=i+1; j<=length-1;j++) {
        if ((*arr)[i].nota > (*arr)[j].nota) {
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

int main(int argc,char**argv){alumn*alumns;

... here goes some other code ...

bubble(&alumns,totalAlumns);

return 0;
Run Code Online (Sandbox Code Playgroud)

}

我的问题是这个算法没有排序任何东西.我很难做交换,我尝试了一切,但没有任何作用:(.任何帮助???

mjv*_*mjv 5

显然,你混淆alumn结构数组数组指针 alumm结构.

Bubble逻辑取代了指针数组,其中main函数似乎用一个结构数组来调用它.

由于alumn结构的大小,对指针执行冒泡排序可能更有效,因为每次交换将需要更少的数据移动(一个指针的3个副本,每个几个字节,而3个副本的列struct,每个200多个字节!).

我建议你修改main()函数的逻辑(没有在问题片段中显示)来引入这样一个指向实际alumn结构的指针数组.(当然,这个指针数组也不会让你自己分配结构,en块(在结构数组中)或单独分配.


在你的坚持下,我在暗示这里主要看起来像生成一个可用于气泡的指针数组(气泡保持不变).
顺便说一句,我宣布 alumn *alumns[]了更容易使用意图的列.这是一样的alumn **alumns.

int main(int argc, char **argv)
{
    alumn *alumns[];   // changed to array of pointers [to alumn structs] 
                       // was pointer to alumn struct, likely to be used as an array thereof

    int MaxNbOfAlumns = some_limit;
    alumns = malloc(sizeof(*alumn) * MaxNbOfAlumns);

    // Load the alumn records (from file or whereever)
    // pseudo code:
    // int i_alumns = 0;  // points to the next free slot in alumns array
    // for each record (in file or whereever...)
    //     alumms[i_alums] = malloc(sizeof(struct alumn));
    //     strcpy(alumms[i_alums]->lastname,  whatever_data);
    //     strcpy(alumms[i_alums]->name,  whatever_otherdata);
    //     alumms[i_alums]->par = some_int_data;
    //     alumms[i_alums]->nota = some_other_int_data;
    //     i_alums++;

... here goes some other code ...

  bubble(alumns, totalAlumns);   // alumns now being an array can be passed as is.

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望保持原始列的变量如前所述,那么可能需要的就是这样,就在调用bubble()之前

  int i;
  alumn *ap_alumns[];   // new variable
  ap_alumns = malloc(sizeof(*alumn) * totalAlumns);
  for (i = 0; i < totalAlumns; i++)
      ap_alums[i] = &alumns[i];
  bubble(ap_alumns, totalAlumns);  
Run Code Online (Sandbox Code Playgroud)

应该强调的一点是,无论其起源如何,传递给bubble()的数组都可以正常排序,但要使用它,您需要取消引用各个指针.
因此,您打算使用旧的数组alumns[123].lastname,您现在需要alumns[123]->lastname (或者ap_alumns[123]->lastname如果您使用第二个版本).