input in red
Displaying contents of *b[]dd
aa
cc
e
f
b
press enter to continue
aa
b
cc
dd
e
input in red
Displaying contents of *b[]dd
aa
cc
e
f
b
press enter to continue
aa
b
cc
dd
e
Try it with the new sort code. (I changed it in the earlier post). Keep in mind that capital letters will always sort out lower than any lower case letters. That can throw you if you're used to case insensitive sorting.
The problem that I see is that your *b[] has "ragged" amounts of char space, for each word.
So b[0] has 5 chars (4 + end of string)
but b[2] only has 2 chars in it.
So when you start sorting, you're toast. b[2] has no room for more than 2 chars in it. You can test this for yourself. Put equal length strings in all of *b[]. The sort works great now. Once you start varying the length of the strings, it's goofed.
Could I interest you in a little index sort, with the same sorter? It would leave everything in place, but it can appear (and be accessed in), sorted order.
Bit of magic there, if you like.
Last edited by Adak; 02-25-2010 at 01:32 PM.
yes that would good to see. The more info I learn the better.
How would I put *b[] into equal lengths? Would there be a set way of doing it?
Enjoy! Works fine.
You would have to use a regular 2D array: b[6][7], or allocate the memory.Code:#include <stdio.h> #include <string.h> int main() { int i, j, temp_num; int index[6]; char temp[20]; char *str[6] = { {"This"}, {"is"}, {"a"}, {"string"}, {"to"}, {"parse"} }; // scanf("%s", str); for(i = 0; i < 6; i++) { printf("\n%s %d", str[i], strlen(str[i])); } //initialize the index array for(i = 0; i < 6; i++) index[i] = i; printf("\n\n"); for(i = 0; i < 6; i++) { for(j = i+1; j < 6; j++) { //normal string sorting: //if((strcmp(str[i], str[j])) > 0) { //strcpy(temp, str[i]); //strcpy(str[i], str[j]); //strcpy(str[j], temp); //sorting by index: if((strcmp(str[index[i]], str[index[j]])) > 0) { temp_num = index[i]; index[i] = index[j]; index[j] = temp_num; } } } printf("\n\n In Sorted Order:"); for(i = 0; i < 6; i++) //print using the index printf("\n%s", str[index[i]]); printf("\n\n Order in the array is unchangedl: "); for(i = 0; i < 6; i++) { printf("\n%s %d", str[i], strlen(str[i])); printf("\n\n\t\t\t press enter when ready"); i = getchar(); return 0; }
Last edited by Adak; 02-25-2010 at 03:21 PM.