In: Computer Science
How do I sort something alphanumerically in C?
consider the example 10abc, 2abc, 2abbbb,b500, a500cd
the output should be a500cd < b500 < 10abc < 2abbbb < 2abc.
another example would be A < AB < A3D < 3DA < 5.
elements are in a linked list
Hi
I have a simple solution or you, see below alogorithm to sort strings, similiarly you can do in it for link list
str[0] will represent one node of list and str[1] is another node of the link list and so on....., please let me know for any clarifications i can help you
step 1:
char str[] ={"b500","a500cd"}
int i = 0, j =0;
for(i=0;i<=2;i++) for(j=i+1;j<=2;j++){ if(strcmp(str[i],str[j])>0){ strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } }
//Revised Answer ,
Now the issue here is actual value of character 0 -9 is less than a - z in he ascii chart so you will face this problem ,
so what we can do is when we get a character from 0 - 9 we will add 123 which is value after 'z' , so the value becomes greater than z and then we can compare the characters ,so now i have revised the alogorithm as below.
for(int i =0 i < count ; i ++){
for( int j =0 ;j < strlen(str[i]); j ++){
char temp1 = str[i][j];
char temp2 = str[i+1][j];
if(temp1 > ='0' && temp1 < ='9'){
temp1 = temp 1 + 123;
}
if(temp2 > ='0' && temp2 < ='9'){
temp2 = temp2 + 123;
}
if (temp1> temp2){
strcpy(temp,str[i]);
strcpy(str[i],str[i+1]);
strcpy(str[i+1],temp);
}else if( temp1 < temp2){
continue;
}else if (temp1 == temp2){
break;
}
}
}