簡體   English   中英

C數組交換中的冒泡排序

[英]Bubble Sort in C array swapping

最近,當我進入這段代碼的交換部分時,我一直遇到這個問題,所以這段代碼要做的是輸入一個數組,並使用冒泡排序方法對其進行排序。 讀取此內容的文本文件有10個數字和名稱。 像這樣:

約翰一書
馬可福音2
馬太福音2
路加福音3
艾薩克4
凱恩5
瑞安7
亞伯2
亞當9
前夕10

但是,當它打印出來時,它顯示如下:

約翰一書
馬可福音2
馬太福音2
亞伯2
亞伯3
亞伯4
亞伯5
亞伯7
亞當9
前夕10
抱歉,問題是為什么它會重復Abel,我該怎么做才能解決?

    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++;
    }
}

而不是這個:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM