1

I wrote the following code to bubble sort a character string. It's displaying garbage values.

main() {
  int n, j, k;
  char a[20], temp;
  // statements to scan the number of items (n) and the string a[n].

  for (j = 1; j < n; j++) {
    for (k = 0; k < n - j; k++) {
      if (a[k] >= a[k+1]) {
        temp = a[k];
        a[k] = a[k+1];
        a[k+1] = a[k];
      }
    }
  }
  printf("The sorted items are: %s",a);
}

What may be the issue?

2
  • Hint: what's n set to? Commented Dec 3, 2014 at 3:49
  • 1
    Show the code for //statements to scan the number of items (n) and the string a[n]. Commented Dec 3, 2014 at 3:50

2 Answers 2

3

In some of the old C compilers, you can't compare characters. A simple solution would be type-casting. As for your code,

main()
{
int n,j,k;
char a[20], temp;
//statements to scan the number of items (n) and the string a[n].

for(j=1; j<n; j++)
{
    for(k=0; k<n-j; k++)
    {
        if((int)a[k]>=(int)a[k+1])
        {
            temp=a[k];
            a[k]=a[k+1];
            a[k+1]=temp;
        }
    }
}
printf("The sorted items are: %s",a);
}

Note that by type-casting, you're comparing the ASCII values of the characters.

Sign up to request clarification or add additional context in comments.

1 Comment

The type casting does not solve the problem, the correct use of temp does. And also without casting to int you are comparing ASCII values.
3

You correctly made a temp-var for swapping the two elements, but forgot to use it! You want:

a[k+1] = temp;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.