gpt4 book ai didi

c - 通过排序函数传递字符串数组

转载 作者:行者123 更新时间:2023-11-30 15:26:14 25 4
gpt4 key购买 nike

我正在尝试在 C 编程中使用排序数组。我有三个数组,arr1、arr2、arr3,它们一起使用来实现:

arr1: arr2: arr3:

4534 97.5 m4W
4554 97.4 m5W
4574 97.6 m6W
3934 97.1 m1W
4054 97.2 m2W
4174 97.3 m3W

我想对这些数组进行排序,以便它们基于第一个数组按从小到大的顺序排列,arr1。

到目前为止,我有一个可以正确排序前两列的函数。但是,我不确定如何对第三列字符串进行排序。这是到目前为止我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void sortArray(float a[], float b[], char c[], int size){
int i, swap;
float temp1, temp2;
char temp3;
do{
swap = 0;
for (i = 0; i < size - 1; i++){//basic sorting for loop
if (a[i]>a[i + 1]){
swap = 1;
temp1 = a[i]; //temporarily stores value of array cell
temp2 = b[i];
temp3 = c[i];
a[i] = a[i + 1]; //swaps the cells
b[i] = b[i + 1];
c[i] = c[i + 1];
a[i + 1] = temp1;//stores value in swapped cell
b[i + 1] = temp2;
c[i + 1] = temp3;
}
}
} while (swap);

}

int main()
{
float arr1[6] = { 4534, 4554, 4574, 3934, 4054, 4174 };
float arr2[6] = { 97.5, 97.4, 97.6, 97.1, 97.2, 97.3 };
char arr3[6][4] = { "m4w", "m5w", "m6w", "m1w", "m2w", "m3w" };

printf("Arrays before sorting:\n");
for (int i = 0; i != 6; i++)
{
printf("%f ", arr1[i]);
printf("%f ", arr2[i]);
printf("%s\n", arr3[i]);
}

sortArray(arr1, arr2, *arr3, 6); ///this is where the sorting function is used

printf("\n\nArrays after sorting:\n");

for (int i = 0; i != 6; i++)
{
printf("%f ", arr1[i]);
printf("%f ", arr2[i]);
printf("%s\n", arr3[i]);
}


system("pause");
return 0;
}

这是输出:

Arrays before sorting:
4534.0 97.5 m4w
4554.0 97.4 m5w
4574.0 97.6 m6w
3934.0 97.1 m1w
4054.0 97.2 m2w
4174.0 97.3 m3w


Arrays after sorting:
3934.0 97.1
4054.0 97.2 4ww
4174.0 97.3 m6w
4534.0 97.5 m1w
4554.0 97.4 m2w
4574.0 97.6 m3w

显然第三列是错误的。我真的不确定如何将字符串数组传递到函数中,并让函数像对前两列那样对其进行排序。任何帮助将不胜感激

最佳答案

这将解决您的问题。更改函数定义参数和代码,如下所示。

void sortArray(float a[], float b[], char c[6][4], int size){
int i, swap;
float temp1, temp2;
char temp3[4];
int k = 0;
do{
swap = 0;
for (i = 0; i < size - 1; i++){//basic sorting for loop
if (a[i]>a[i + 1]){
swap = 1;
temp1 = a[i]; //temporarily stores value of array cell
temp2 = b[i];
for ( k=0; k < 4 ; k++ ) { //Copying the c[i] to temp
temp3[k] = c[i][k];
}
a[i] = a[i + 1]; //swaps the cells
b[i] = b[i + 1];
for ( k=0; k < 4 ; k++ ) { //Copying the c[i+1] to c[i]
c[i][k] = c[i+1][k];
}
a[i + 1] = temp1;//stores value in swapped cell
b[i + 1] = temp2;
for ( k=0; k< 4 ; k++ ) { //Copying the temp to c[i+1]
c[i+1][k] = (char)temp3[k];
}
}
}
} while (swap);
}

您可以在Sorting Multiple Arrays查看运行示例

关于c - 通过排序函数传递字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27456474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com