2012-12-06 41 views
0

我想按降序對intchar(從一個類)的數組進行排序。這些是學生的姓名和成績。使用冒泡排序從類中排序2D Char和Int數組?

的類定義爲:

class Student { 
public: 
    char name[20]; 
    int grades; 
}; 

numCount是記錄數的增量值。

void bubble_sort(Student theResults[], int numCount) 
{ 
    bool swapped = true; 
    while(swapped) 
    { 
    swapped = false; 
    for(int i=1;i<numCount;i++) 
    { 
     if(theResults[i-1].grades < theResults[i].grades) 
     { 
     int tempHold = theResults[i-1].grades; 
     theResults[i-1].grades = theResults[i].grades; 
     theResults[i].grades = tempHold; 
     swapped = true; 
     } 
    } 
    } 

我遇到的問題是,int值(牌號)在循環後正確排序,但得到的名字有困難要正確分配,以配合等級。

我已經使用了下面的代碼,但它不起作用,因爲它顯示學生不正確的成績。

char* title_temp = theResults[i-1].name; 
theResults[i-1].name[20] = theResults[i].name[20]; 
theResults[i].name[20] = title_temp[20]; 

回答

1

我覺得你的問題是在這裏:

if(theResults[i-1].grades < theResults[i].grades) 
{ 
    int tempHold = theResults[i-1].grades; 

    theResults[i-1].grades = theResults[i].grades; 

    theResults[i].grades = tempHold; 

    swapped = true; 
} 

你真正想要做的是

if(theResults[i-1].grades < theResults[i].grades) 
{ 
    Student tempHold = theResults[i-1]; 

    theResults[i-1] = theResults[i]; 

    theResults[i] = tempHold; 

    swapped = true; 
} 

之前所有你改變的是成績值而不是名字,這將切換整個學生對象,並應該親duce你正在尋找的輸出

+0

Siegester,謝謝。代碼完美工作。謝謝你的幫助。 – MacKey

1

的問題是,你需要交換對象,成績只能作爲一個關鍵引導排序,試試這個:

void bubble_sort(Student theResults[], int numCount) 
{ 

    Student tempHold; 
    bool swapped = true; 
    while(swapped) 
    { 
     swapped = false; 
     for(int i=1;i<numCount;i++) 
     { 
      if(theResults[i-1].grades < theResults[i].grades) 
      { 
       tempHold = theResults[i-1]; //swap the objects, not just the grades. 

       theResults[i-1]= theResults[i]; 

       theResults[i] = tempHold; 

       swapped = true; 
      } 
     } 
    }} 

但是,如果必須另外複製的成員,然後交換等級:

char temp[20]; 
strcpy(temp ,theResults[i-1].name); 
strcpy(theResults[i-1].name,theResults[i].name);  
strcpy(theResults[i].name,temp); 

而不是使用

char* title_temp = theResults[i-1].name; // <-wrong 
    theResults[i-1].name[20] = theResults[i].name[20];//20 is invalid index 
    theResults[i].name[20] = title_temp[20]; //this is just 1 element out of the whole array 

這是錯誤的,由於許多原因。

+0

axiom,優秀:D同樣工作就像一個魅力。感謝您的幫助和建議。 PS抱歉只能將1標記爲正確答案,並且完成了第一篇文章,即使所有三篇文章都是正確的。抱歉。 – MacKey

1

您必須使用循環一次性複製整個char塊,每個元素,或者您可以使用memcpy。

你也可以使用你的類的淺表副本

void bubble_sort(Student theResults[], int numCount) 
{ 


    bool swapped = true; 
    while(swapped) 
    { 
     swapped = false; 
     for(int i=1;i<numCount;i++) 
     { 
      if(theResults[i-1].grades < theResults[i].grades) 
      { 
       Student tempHold = theResults[i-1]; 

       theResults[i-1]= theResults[i]; 

       theResults[i] = tempHold; 

       swapped = true; 
      } 
     } 
    } 
} 
+0

Nico,上面的代碼也很完美。感謝您的時間和help.PS對不起,只能標記1作爲正確的答案,我做了第一篇文章,即使所有三個帖子都是正確的。抱歉。 – MacKey