# Thread: Sorting an array of strings

1. ## Sorting an array of strings

Hi,

I can't figure out what's wrong with this code, but the selection sort isn't doing it's job (nothing gets sorted). I think there's probably a lot wrong with it, but I can't narrow it down. Everything else works. But I think the bottom line is that I'm not sure how to make selection sort work when it's an array of strings involved.

Here's the selection sort part:
Code:
```char array[NUM][LEN] = {0};

int x, y, index_of_min;
int temp;

for (x=0; x<LEN-1; x++)
{
int index_of_min = x;

for(y=x; y<LEN; y++)
{
if(array[index_of_min]>array[y])
{
index_of_min = y;
}
}
}

temp = *array[x];
*array[x] = *array[index_of_min];
*array[index_of_min] = temp;
}```

2. There are a few problems:

First, I think you have a brace out of whack. Your swap code is happening outside of the for (x) loop. You need to move it inside somewhere.

Second, I think your loops should be terminate when x < NUM - 1 and y < NUM.

Third, you re-declare index_of_min inside your for (x = 0; ...) loop, giving it scope for just that loop. On each iteration of that loop, you effectively have a new index_of_min. Just have the one declaration at the top of the function and set it to x at the top of your for(x) loop.

Fourth, you can't compare strings using the <, >, ==, etc operators. That compares the address of the start of the string, not the strings themselves. You need to use strcmp.

Fifth, when you do get the rest working, your swap code wont work. You declared a 2-d array of chars, not a 1-d array of char pointers, so you can't use *array[x] = *array[index_of_min]. That is swapping only the first characters. You will have to declare temp as a char array and swap using strcpy, like so:
Code:
```char    temp[LEN];
...
strcpy(temp, array[x]);  // "assign" temp the string in array[x]```

3. Thanks a million.