我想在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
顯然,第三列是做錯了。我真的不知道如何將字符串數組傳遞給函數,並讓函數按照前兩列那樣排序。任何幫助,將不勝感激
sortArray()錯誤地訪問字符數組。你可能想要'c [i * 4 + 0],c [i * 4 + 1],c [i * 4 + 2]' – Basilevs 2014-12-13 07:18:51