Christian Halim
Christian Halim

Reputation: 117

Bubble Sort with Strings, but it's not sorting well

I'm trying to sort an array of strings into an ascending order

Abcdefg
Ultimate
UMN 
Bawaw

i expect the result should be into:

Abcdefg
Bawaw
Ultimate
UMN

I found that bubble sort is sorting strings like :

Abcdefg
Bawaw
UMN
Ultimate

And when i try to bypass it, by turning everything into an uppercase / lowercase strings, but if i add the data, it became juggled

#include<stdio.h>
#include<string.h>

int main(int argc, char **argv){

    char data[8][50] = {"Abcdefg","Ultimate","UMN", "Bawaw", "Ultima Sonora", "UMN Medical Centre", "Ultima Toys","BACD"};
    char temp[10];
    int i, j;

    printf("Original data = \n");
    for(i=0; i<8; i++){
        printf("%s\n", data[i]);
    }

    printf("\n");
    for(i = 0; i < 8; i++){
        for(j = 0; j < 50; j++){
            if(data[i][j] >= 65 && data[i][j] <= 90){
                data[i][j] += 32;
            }
        }
    }


    for(i = 0; i <8 ; i++){
        for(j = i+1; j < 8; j++)
        if(strcmp(data[i], data[j])>0){
            strcpy(temp, data[i]);
            strcpy(data[i],data[j]);
            strcpy(data[j], temp);
        }
    }
    printf("Sorted data = \n");
    for(i=0; i<8; i++){
        printf("%s\n", data[i]);
    }
    return 0;
}

Do anyone have a clue what's going on there?

Upvotes: 1

Views: 181

Answers (2)

hanie
hanie

Reputation: 1885

first note that temp doesn't have enough space to hold some of your strings , so use char temp[50]. also since ASCII code of l is smaller than m the result you are excepting is true , so is your program , but since you have overflow ,the program will have undefined behavior. which means anything can happen.

Read this link How dangerous is it to access an array out of bounds?also it's not bad to take look here how strcmp() works

Upvotes: 3

Hitokiri
Hitokiri

Reputation: 3699

One more thing i see in your code is in the part of uppercase / lowercase strings.

for(i = 0; i < 8; i++){
        for(j = 0; j < 50; j++){
            if(data[i][j] >= 65 && data[i][j] <= 90){
                data[i][j] += 32;
            }
        }
    }

you should use j < strlen(data[i]. You can also use tolower function as the comment above.

It becomes:

for(i = 0; i < 8; i++){
        for(j = 0; j < strlen(data[i]); j++){
            data[i][j] = tolower(data[i][j]);
        }
    }

Upvotes: 1

Related Questions