# Thread: Sorting a string using bubble sort?!

1. ## Sorting a string using bubble sort?!

I want to sort an array of strings. To do this I must use the bubble sort method correct? I just pull out the first letter of each string convert it to it's ascii value then sort correct?

but how do I tell it to only pull out the first letter of the string? I would also need to sure the string header and copy the strings instead of using tmp. correct?

void sort(char a[], int n){
int i, j

for (i=0; i < n - 1; ++i)
for (j = n - 1; i < j; --j)
if (a[j-1] > &a[j])
swap(&a[j-1], &a[j]);
}

void swap(int *p, int *q)
{
int tmp;

tmp = *p;
*p = *q;
*q = tmp;
}

2. Use strcmp(). It returns -1, 0, or 1 depending on if the first string is less than, equal to, or greater than the second string.

3. ## Look...

Look my example, I'll sort strings with an index help.
Code:
```#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ROW 5
#define SIZE 30

void swap(int idx[], int j);
void printf_string(const char sStrs[ROW][SIZE], int idx[]);

int main(void)
{
const char sStrs[ROW][SIZE] = {
"my fool string",
"another fool idiot string",
"blah, nothing",
"need to say more",
"in a year or twice",
};

int idx[ROW] = {0,1,2,3,4};
int i,j;

printf("Before sorting: ");
printf_string(sStrs, idx);

for(i=0; i<ROW; ++i) {
for(j=0; j<ROW - (i+1); ++j)
if(strcmp(sStrs[idx[j]], sStrs[idx[j+1]]) > 0)
swap(idx, j);
}

printf("\nAfter sorting: ");
printf_string(sStrs, idx);
system("PAUSE");
return 0;
}

void swap(int idx[], int j)
{
int tmp;

tmp = idx[j];
idx[j] = idx[j+1];
idx[j+1] = tmp;
}

void printf_string(const char sStrs[ROW][SIZE], int idx[])
{
int i;

for(i=0; i<ROW; ++i)
printf("sStrs[%d] = %s\n",i,sStrs[idx[i]]);
}```

4. Originally posted by orbitz
Use strcmp(). It returns -1, 0, or 1 depending on if the first string is less than, equal to, or greater than the second string.
No it doesn't. I suggest you read the manual for that function again.

5. 7.21.4.2 The strcmp function

Synopsis
1 #include <string.h>
int strcmp(const char *s1, const char *s2);

Description
2 The strcmp function compares the string pointed to by s1 to
the string pointed to by s2.

Returns
3 The strcmp function returns an integer greater than, equal to,
or less than zero, accordingly as the string pointed to by s1 is
greater than, equal to, or less than the string pointed to by s2.

6. Returns 3 The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.
Unless I am confused, this is what I said.

7. >>Unless I am confused, this is what I said.
You said -1, 0, or 1. strcmp() doesn't have to return those exact values except for 0. :-)