2015-02-10 59 views
0

當我開始交換這段代碼的一部分時,我一直有這個問題,所以這段代碼做的是輸入一個數組並使用冒泡排序方法對它進行排序。讀取此文本文件有10個數字和名稱。像這樣:Bubble Sort in C array swapping

約翰1
標記2
馬修2
路3
伊薩克4
凱恩5
瑞恩7
阿貝爾2
亞當9
伊芙10

然而當它打印出來時,它會顯示:

約翰1
標記2
馬修2
阿貝爾2
阿貝爾3
阿貝爾4
阿貝爾5
阿貝爾7
亞當9
伊芙10
對不起,問題是爲什麼它重複阿貝爾,我能做些什麼來解決它?

void bubbleSort (Word q){ 
    int last = 9; 
    int Swapped = 1; 
    int i = 0; 
    int m = 0; 
    char* temp = "Hello"; 
    printf("Temp is: %s \n", temp); 
    int tempA; 
    while (Swapped == 1){ 
     Swapped = 0; 
     i = 1; 
     while (i < last){ 
      printf("%d \n", i); 
      if (q.data[i] > q.data[i+1]) { 
       printf("Hello: %d \n", i); 
       //Copy Name of Element 
       temp = q.name[i]; 
       strcpy(q.name[i], q.name[i+1]); 
       strcpy(q.name[i+1] , temp); 

       //Copy Data of corresponding element 
       tempA = q.data[i]; 
       q.data[i] = q.data[i+1]; 
       q.data[i+1] = tempA; 
       Swapped = 1; 

      } 
      i = i + 1; 
     } 
     last = last - 1; 
    } 
    last = 9; 
    while (m <= last){ 
     printf("Name: %s, Data: %d \n", q.name[m], q.data[m]); 
     m++; 
    } 
} 
+0

要排序依據的'結構data'部件上。所以,你的輸出是基於該成員進行排序的。你的問題是什麼? – askmish 2015-02-10 07:54:23

+1

@askmish:盧克3似乎從輸出中缺失,但我同意這個問題不是很清楚。 – 2015-02-10 07:56:28

回答

0

取而代之的是:

char* temp = "Hello"; 

你應該這樣做無論是這樣的:

char *temp = malloc(MAX_NAME_LEN*sizeof(char)); 
//check if allocation of memory was successful or handle exceptions 

或者,這樣的:

char temp[MAX_NAME_LEN]; 

然後

strcpy(temp, "Hello"); 

您需要將字符串存儲到一個臨時變量,指向一個實際的內存,使用它在串交換操作,在代碼的後面部分。

,而不是這一點,:

//Copy Name of Element 
    temp = q.name[i];//HERE you are storing a pointer to the address, not the actual string. Both q.name[i] and temp point to the same memory 
    strcpy(q.name[i], q.name[i+1]);//Both q.name[i] and the temp pointer, with the string at q.name[i+1]. the original string in q.name[i] is lost. 
    strcpy(q.name[i+1] , temp);//You are copying the same content as in q.name[i+1]. You are not copying the original content of q.name[i] 

做到這一點:

//Copy Name of Element 
strcpy(temp, q.name[i]);//HERE you are storing the actual string 
strcpy(q.name[i], q.name[i+1]);//q.name[i] and temp contain distinct strings 
strcpy(q.name[i+1], temp);//HERE you are copying the orginal string of q.name[i]