bubble sort a character array in alphabetic order in c

41,386

Solution 1

Fixing your code

First of all, there are some pretty serious fundamental issues with your code. Before we tackle those though, let's just fix what you have so far. Your sorting loop seemed to be half sorting the a array and half sorting the b array. you also never initialized the b array to contain any values. Here is a corrected version of your code:

#define CLASS_SIZE 10
#include <stdio.h>

void bubbleSortAWriteToB(const char a[], char * b[]);

int main(void){
    int i;

    // initialize array
    char * s_letters[CLASS_SIZE];
    char letters[CLASS_SIZE] = {'a','r','p','b','r','c','x','e','w','j'};
    // sort array
    bubbleSortAWriteToB(letters,s_letters);

    // print sorted array
    for (i=0;i<CLASS_SIZE;i++){
        printf("%c\n", *s_letters[i]);
    }

    return 0;
}

void bubbleSortAWriteToB(const char a[], char * b[]){
    char * temp;
    int i,j;

    // initialize b array to hold pointers to each element in a
    for (i=0;i<CLASS_SIZE;i++){
        b[i] = (char *)(a) + i;
    }

    // in-place sort the b array
    for(i=0;i<CLASS_SIZE;i++){
        for(j=i+1;j<CLASS_SIZE-1;j++){
            if(*b[j-1]>*b[j]){
                temp = b[j];
                b[j] = b[j-1];
                b[j-1] = temp;
            }
        }   
    }
}

The fix was to initialize the b array with points to a, and then sort the b array in-place by comparing the corresponding values in the a array.


Simplifying the code

In your original code, the strategy was to have an array of pointers (b) that would point to the elements in a, and then get sorted. This was unnecessary here though, because characters are smaller than pointers, so letting b be an array of characters is more space-efficient and simpler.

Also, your spacing was very squished-together and somewhat difficult to read. Here's a solution that uses b as an array of characters instead of pointers, and offers improved spacing. Also, declaring the function above was not necessary. It suffices to define the function and declare it once.

#define CLASS_SIZE 10
#include <stdio.h>

void bubbleSortAWriteToB(const char a[], char b[]){
    char temp;
    int i,j;

    // initialize b array to hold pointers to each element in a
    for (i = 0; i < CLASS_SIZE; i++){
        b[i] = a[i];
    }

    // in-place sort the b array
    for(i = 0; i < CLASS_SIZE; i++){
        for(j = i + 1; j < CLASS_SIZE - 1; j++){
            if(b[j-1] > b[j]){
                temp = b[j];
                b[j] = b[j-1];
                b[j-1] = temp;
            }
        }   
    }
}

int main(void){
    int i;

    // initialize array
    char s_letters[CLASS_SIZE];
    char letters[CLASS_SIZE] = {'a','r','p','b','r','c','x','e','w','j'};

    // sort array
    bubbleSortAWriteToB(letters, s_letters);

    // print sorted array
    int i;
    for (i = 0; i < CLASS_SIZE; i++){
        printf("%c\n", s_letters[i]);
    }

    return 0;
}

Solution 2

Your s_letters is not properly initialized, yet you access it in:

*b[j] = a[j-1];
*b[j-1] = temp;

It's a segfault.

Solution 3

I compiled this with gcc -g and ran it through Valgrind, and got this:

==54446==  Non-existent physical address at address 0x100000000
==54446==    at 0x100000EB0: bubbleSortAWriteToB (x.c:20)
==54446==    by 0x100000DFE: main (x.c:9)

Line 20 is this:

*b[j] = a[j-1];

char *b[] is an array of char pointers, but you're trying to put something in the pointers without initializing them. If you really want to do this, you'd need to:

b[j] = malloc(sizeof(*b[j])); // Create some space for a char
*b[j] = a[j-1]; // Put the char in that space

But, I don't think that's what you actually want. If you just change it to char b[], and remove all of your *'s, it works fine.

Share:
41,386
Umut
Author by

Umut

Updated on July 07, 2022

Comments

  • Umut
    Umut almost 2 years

    I'm trying to bubble sort a character array in alphabetic order. My code is as follows:

    #define CLASS_SIZE 10
    #include <stdio.h>
    
    void bubbleSortAWriteToB(const char a[], char *b[]);
    
    int main(void){
        char *s_letters[CLASS_SIZE];
        char letters[CLASS_SIZE] = {'a','r','p','b','r','c','x','e','w','j'};
        bubbleSortAWriteToB(letters,s_letters);
            return 0;
    }
    
    void bubbleSortAWriteToB(const char a[], char *b[]){
        char temp;
        int i,j;
        for(i=0;i<CLASS_SIZE-1;i++){
            for(j=1;j<CLASS_SIZE;j++){
                if((int)a[j-1]>(int)a[j]){
                    temp = a[j];
                    *b[j] = a[j-1];
                    *b[j-1] = temp;
    
                }
    
        }
    
      }
    }
    

    It doesn't give any kind of error but when i run it it gets stuck like it's kinda in a inifinte loop. But from what i can see it isn't that either. Can you help me out?

    • Brendan Long
      Brendan Long over 12 years
      It's not an infinite loop, it's a segmentation fault.
    • Brendan Long
      Brendan Long over 12 years
      It means that you're trying to access memory that you shouldn't be.
    • Jonathan Grynspan
      Jonathan Grynspan over 12 years
      It means it was a segmentation fault. ;) Is this homework?
    • Michael Dorgan
      Michael Dorgan over 12 years
      Your second loop isn't setup properly for a bubble sort. It should be comparing against i somehow to reduce the work it does by half. Also, your swap is messed up. Use better var names to help yourself out a bit. a,b,i,j are hard for the human mind to parse. Fortran77 this is not.
    • Brendan Long
      Brendan Long over 12 years
      You may find this question useful: stackoverflow.com/questions/859634/…
    • Adrian McCarthy
      Adrian McCarthy over 12 years
      Aren't these "find my bug" questions better suited to codereview.stackexchange.com? Interestingly, that's not one of the choices if you vote to close a question as "off topic". Perhaps "too localized" is appropriate, but migrating seems less harsh than outright closing.
    • Yinda Yin
      Yinda Yin over 12 years
      @AdrianMcCarthy: Code troubleshooting questions are specifically off-topic at CodeReview.SE. They want working code.
  • Michael Dorgan
    Michael Dorgan over 12 years
    Making those pointers means you didn't allocate a char array to place your stuff into, but an array of char *. Not nearly the same thing.
  • Brendan Long
    Brendan Long over 12 years
    @UmutŞenaltan Read this question to see how to make a pointer to an array of char.
  • Brendan Long
    Brendan Long over 12 years
    @UmutŞenaltan - My guess is that what you really want is just a char*.
  • David Buck
    David Buck almost 4 years
    This post has a comprehensive, accepted, answer with clear explanations that was posted 8 years ago. Whilst alternative answers are always welcome, their value (and their likelihood of receiving upvotes) will be much higher if you include an explanation of how your answer works and how it improves over existing answers, or what alternatives it offers.
  • Gerhardh
    Gerhardh almost 4 years
    Also noteworthy: The question is tagged with C language tag. Answers should provide solutions in the relevant programming language. Your code cannot be compiled with a C compiler.