如何解决C字符串数组冒泡排序返回输入作为输出
在我的函数中,我得到了一个字符串数组,它需要通过特定的规则集进行排序,该规则集也给出了 - 主函数有效,规则比较也有效,但冒泡排序不断将输入作为输出返回,我不明白为什么。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
void swap(char** s1,char** s2)
{
char** temp = s1;
s1 = s2;
s2 = temp;
}
main()
{
int i,j;
char** arr_of_strings = malloc(3 * sizeof(char*));//I allocated the array
arr_of_strings[0] ="wonder_woman";//with malloc and loops originally.
arr_of_strings[1] ="batman";
arr_of_strings[2] ="superman";
for (i = 0; i <2; i++)//the bubble array process:
{
for (j = 0; j < 3 - i - 1; j++)
{
if (strcmp(arr_of_strings[i],arr_of_strings[j]) > 0)
{
swap(&arr_of_strings[j],&arr_of_strings[j + 1]);
}
}
}
printf("The sorted strings are:\n"); //printing the function
for (int k = 0; k < 3; k++) {
printf("%s\n",arr_of_strings[k]);
}
}
输出示例:
The sorted strings are:
wonder_woman
batman
superman
解决方法
检查这行,比较 i 和 j ,但交换 j 和 j+1
if (arr_of_strings[i]> arr_of_strings[j]) //simplification
{
swap(&str_arr[j],&str_arr[j + 1]);
}
,
我认为您的交换功能或调用方式有问题。 无论如何,这个实现是有效的:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define SIZE 3
int main()
{
int i,j; int n=SIZE; //n is a user input in the original program.
char temporary_string[32];
char* arr_of_strings[SIZE];
char* temp = NULL;
//input data
for (int l = 0; l < 3; l++)
{
scanf("%s",temporary_string);
arr_of_strings[l] = malloc(((strlen(temporary_string) + 1) *sizeof(char)));
strcpy(arr_of_strings[l],temporary_string);
temporary_string[0] = '\0';
}
//the actual sort
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < SIZE - i - 1; j++)
{
if (strcmp(arr_of_strings[j],arr_of_strings[j + 1]) > 0) //simplification
{
//swap
temp = arr_of_strings[j];
arr_of_strings[j] = arr_of_strings[j + 1];
arr_of_strings[j + 1] = temp;
}
}
}
printf("The sorted strings are:\n");
for (int i = 0; i < n; i++) {
printf("%s\n",arr_of_strings[i]);
}
// free allocated memory
for (int i = 0; i < n; i++) {
free(arr_of_strings[i]);
}
}
希望对您有所帮助,如果您有疑问,我很乐意回答=)
,您的 swap
函数实际上并未交换其参数指向的项目。改为:
void swap(char** s1,char** s2)
{
char* temp = *s1;
*s1 = *s2;
*s2 = temp;
}
此外,您的 main
函数正在比较不相邻的项目但交换相邻的项目,因此无法正确排序。将代码的相关部分更改为:
if (strcmp(arr_of_strings[j],arr_of_strings[j + 1]) > 0)
{
swap(&arr_of_strings[j],&arr_of_strings[j + 1]);
}
按升序排序。
可以通过跟踪最后交换项目的位置并在不交换任何项目的通过后完成排序来优化冒泡排序:
i = 3; // sorting first 3 items
while (i > 1)
{
int last = 0;
for (j = 0; j < i - 1; j++)
{
if (strcmp(arr_of_strings[j],&arr_of_strings[j + 1]);
last = j + 1;
}
}
i = last;
}
,
您的 swap
函数没有做任何事情。
类似于这个交换两个整数的函数:
void swap(int a,int b)
{
int temp = a;
a = b;
b = temp;
}
如果你这样称呼它:
int a = 2,b = 3;
swap(a,b);
a 和 b 仍然包含相同的值。
这是您的 swap
的正确代码:
void swap(char** s1,char** s2)
{
char *temp = *s1;
*s1 = *s2;
*s2 = temp;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。