[英]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.