hey guys,
I tried to sort an array according to another array, and although nothing wrong was in the syntex nor the logic,
the application did not work.
for example, If I try to sort an array with bubble sorting , it works fine:
Code:
#include <stdio.h>
int main (void){
int arr[]={5,3,7,9,10};
int i,j;
for (i=0;i<5;i++)
for (j=0;j<4;j++) //I know it could be optimized, it's good enough for the example
if (arr[j]>arr[j+1]){
int x=arr[j];
arr[j]=arr[j+1];
arr[j+1]=x;
}
return 0;
but now I have 2 arrays - one is strings array (2 dimentional array of char, or array of cahr pointers, I tried them both) and the other
is integers array.
I try to sort the integer array according to the first char of the string array . there IS something happening there - but
aventually the array is sorted wrong.
I googled this problem and I saw many people refering to this issue as common bug in C language. the code itself is good and should
work. I don't know how to pass this issue.
help is needed please.
Code:
#include <stdio.h>
int main (void){
char *arr[]={"zebra","owl","giraff","ants","pony"};
int arr2[]={ 1, 2, 3, 4, 5};
int i,j;
for (i=0;i<5;i++)
for (j=0;j<4;j++) //I know it could be optimized, it's good enough for the example
if ((int)arr[j][0]>(int)arr[j+1][0]){
int x=arr2[j];
arr2[j]=arr2[j+1];
arr2[j+1]=x;
}//the only difference from the last example that this is not the same array.
for (i=0;i<5;i++)
printf ("%d\n",arr2[i]);
return 0;
}
the output :
2
3
4
1
5
thanks in advanced