2010-11-24 102 views
1

如何在函數中對char firstName進行排序,並且已經從文本文件中讀入名稱,並且還可以使用外部庫 所有學生的名字都以文本文件,該文件被讀入學生的陣列記錄如何使用C語言對結構中的char名稱進行排序

struct student{ 
    char*lastName; /*name of the student*/ 
    char*firstName; 
    int age;  /*age of the student*/ 
    float grade[3]; 
} 
+0

您可以通過選擇並按下CTRL + K來格式化代碼。使用預覽。 – EboMike 2010-11-24 22:10:05

+0

此外,您的問題沒有提供足夠的信息。你有什麼樣的陣列/集合?這個結構沒有告訴我們任何東西。 – EboMike 2010-11-24 22:10:41

回答

0

最簡單的方式,假設你不允許使用外部庫,是冒泡。編寫一個函數來確定struct student的數組是否已經排序。然後編寫一個遍歷這個數組的函數,比較相鄰的學生對。如果它們出現故障,請交換它們。使用第一個函數的結果作爲while循環的條件子句,第二個函數作爲主體。

如果您可以使用它,那麼從stdlib.hqsort()是迄今爲止最好的方法。

+0

插入排序通常是觸摸更簡單,觸摸更快。此外,`qsort()`不是外部庫,但包含在C標準庫中。 – 2010-11-24 22:30:37

4

qsort函數通常用於C中對數組進行排序。其中一個參數是指向比較函數的指針。編寫該函數,以便以任何您想要的方式比較這兩個指針。您甚至可以使用不同的比較函數,以便在運行時選擇將應用的選項。

int StudentCompare(const void * elem1, const void * elem2) 
{ 
    const struct student * left = (const struct student *) elem1; 
    const struct student * right = (const struct student *) elem2; 
    int result; 
    result = strcmp(left.firstName, right.firstName); 
    if (result == 0) 
     result = strcmp(left.lastName, right.lastName); 
    return result; 
} 
相關問題