Bubble Sort in C array swapping

孤街醉人 提交于 2020-01-17 04:13:08

问题


I have been having this problem lately when I get to the swapping part of this code, so what this code does is inputs an array and sorts it using the bubble sort method. The text file that reads this in has 10 numbers and names. Like this:

John 1
Mark 2
Matthew 2
Luke 3
Issac 4
Kane 5
Ryan 7
Abel 2
Adam 9
Eve 10

However when it prints it out, it shows this:

John 1
Mark 2
Matthew 2
Abel 2
Abel 3
Abel 4
Abel 5
Abel 7
Adam 9
Eve 10
Sorry, the question is why is it repeating Abel, and what can i do to fix it?

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

回答1:


Instead of this:

char* temp = "Hello";

You should do either this:

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

Or, this:

char temp[MAX_NAME_LEN];

And then

strcpy(temp, "Hello");

You need to store the string to a temp variable, pointing to an actual memory, to use it in string swapping operation, in later part of the code.

And instead of this:

   //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]

do this:

//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]


来源:https://stackoverflow.com/questions/28426567/bubble-sort-in-c-array-swapping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!