Vote count:
0
I have 2 arrays which i want to sort together e.g. 1 is a character A-Z and the other is an ID number: 1,2,3...
char arr1[3][10] = {C, B, A}; int arr2[3] = {2,1,2};
The code i have below sorts the 2nd array numerically from lowest to highest, and sorts the 1st array together/accordingly.
array that is unordered:
Charlie 2
Bravo 1
Aplha 2
Bravo 1
Charlie 2
Aplha 2
MY QUESTION is that how can i sort arr1 alphabetically if there are duplicates in arr2. You can see below Alpha and Charlie flip as they have duplicates values in arr2, this is what i want my output to look like.
Bravo 1
Aplha 2
Charlie 2
Below is my code. Does anyone know how to fix the code to do this function of sorting arr1 in alphabetical order if arr2 has duplicates.
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return strcmp(a, b);
}
void sort(long sz, char arr1[][5], int arr2[])
{
long i;
long j;
char arr1temp[5];
int arr2temp;
for(i=1; i<sz; ++i) {
j=i;
while(j>0 && arr2[j-1] > arr2[j]) {
arr2temp = arr2[j-1];
arr2[j-1] = arr2[j];
arr2[j] = arr2temp;
strcpy(arr1temp, arr1[j-1]);
strcpy(arr1[j-1], arr1[j]);
strcpy(arr1[j], arr1temp);
j = j-1;
}
}
}
int main()
{
int i,j,count;
char arr1[3][5] = {"C", "B", "A"};
int arr2[3] = {2,1,2};
printf("ordered list\n");
for (i=0;i<3;i++)
printf("%s\t%d\n",arr1[i],arr2[i]);
printf("unordered list\n");
sort(3, arr1, arr2);
for (i=0;i<3;i++)
printf("%s\t%d\n",arr1[i],arr2[i]);
}
Output:
unordered list
C 2
B 1
A 2
ordered list
B 1
C 2
A 2
asked 21 secs ago
sort 2 arrays simultaneously in C
Aucun commentaire:
Enregistrer un commentaire