简体   繁体   中英

Bubble sorting a character array

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?

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

a[k+1] = temp;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM