Reputation: 11
Trying to use a bubble sort to put a word into alphabetical order. can anyone find the error in my code, I am calling it but it doesn't seem to be doing what it should
void alphasort(char *word, int length)
{
int i, j, k;
for(i=0; i<length-1; ++i)
{
for(j=0; j<length-i-1; ++j)
{
if (array[j] > array[j+1])
{
k= array[j];
array[j] = array[j+1];
array[j+1] = k;
}
}
}
}
It simply returns the original word
Upvotes: 0
Views: 82
Reputation: 306
You have not defined the variable array
. Try this instead:
void alphasort(char *word, int length)
{
int i, j, k;
for(i=0; i<length-1; ++i)
{
for(j=0; j<length-i-1; ++j)
{
if (word[j] > word[j+1])
{
k= word[j];
word[j] = word[j+1];
word[j+1] = k;
}
}
}
}
Upvotes: 1
Reputation: 10385
There is nothing wrong with the logic you are using.
The only fault is, you have an undefined variable, array
. Either replace all the array
instances with word
, or change char *word
to char *array
.
Code:
void alphasort(char *array, int length)
{
int i, j, k;
for(i=0; i<length-1; ++i)
{
for(j=0; j<length-i-1; ++j)
{
if (array[j] > array[j+1])
{
k= array[j];
array[j] = array[j+1];
array[j+1] = k;
}
}
}
}
Upvotes: 1