I am trying to use a sorting array in C programming. I have three arrays, arr1, arr2, arr3, that are used together to make this:
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
I want to sort these arrays so that they are in order from least to greatest based on the first array, arr1.
So far, I have a function that sorts the first two columns correctly. However, I'm not sure how to go about sorting the third column of strings as well. Here is my code so far:
#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;
}
This is the output:
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
Clearly the third column is done wrong. I'm really not sure how to pass the array of strings into the function and have the function sort it like it did with the first two columns. Any help would be appreciated
c[i*4+0], c[i*4+1], c[i*4+2]