0

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?

strcat
  • 5,376
  • 1
  • 27
  • 31
Umut
  • 409
  • 3
  • 7
  • 20
  • It's not an infinite loop, [it's a segmentation fault](http://codepad.org/7BwJOikP). – Brendan Long Mar 21 '12 at 17:38
  • It means that you're trying to access memory that you shouldn't be. – Brendan Long Mar 21 '12 at 17:42
  • It means it was a segmentation fault. ;) Is this homework? – Jonathan Grynspan Mar 21 '12 at 17:42
  • 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. – Michael Dorgan Mar 21 '12 at 17:42
  • You may find this question useful: http://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation – Brendan Long Mar 21 '12 at 17:47
  • Aren't these "find my bug" questions better suited to http://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. – Adrian McCarthy Mar 21 '12 at 18:31
  • @AdrianMcCarthy: Code troubleshooting questions are specifically off-topic at CodeReview.SE. They want *working* code. – Robert Harvey Mar 21 '12 at 18:55

5 Answers5

2

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;
}
Cam
  • 14,930
  • 16
  • 77
  • 128
1

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.

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
  • 1
    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. – Michael Dorgan Mar 21 '12 at 17:46
  • @UmutŞenaltan Read [this question](http://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation) to see how to make a pointer to an array of char. – Brendan Long Mar 21 '12 at 17:48
  • @UmutŞenaltan - My guess is that what you really want is just a `char*`. – Brendan Long Mar 21 '12 at 18:00
1

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.

Fred
  • 16,367
  • 6
  • 50
  • 65
0

Bubble sort

Console: Input: "face321" OutPut: "123acef"

    #include <stdio.h>

int main(){

    char c[80] = "0";
char temp = '0';
int offSet = 0;
int i = 0;
int j =0;
int count =0;

printf("Enter first string: ");
gets(c);

while (*(c + offSet) != '\0') {
    count++;
    offSet++;
}



for (i = 0; i < count; i++) {
for (j = 0; j < count - 1; j++) {


    if (c[j]>c[j + 1]) {

        temp = c[j];
        c[j] = c[j + 1];
        c[j + 1] = temp;

    }

}

}
    puts(c);
    return 0;
}
Marcia Ong
  • 781
  • 8
  • 15
0
#include<iostream>
using namespace std;
int main(){
cout<<"Enter the size of array";
int n;
cin>>n;
cout<<"enter elements";
char arr[n];
for(int i=0;i<n;i++){
    cin>>arr[i];
}
for(int i=0;i<n-1;i++){
    for(int j=i+1;j<n;j++){
        if(arr[i]<arr[j]){
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
 }
cout<<"sorted array in descending ";
for(int i=0;i<n;i++){
    cout<<arr[i]<<" ";
}
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
  • 1
    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. – David Buck Aug 19 '20 at 09:41
  • 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. – Gerhardh Aug 19 '20 at 09:43