Home > Net >  A function that sorts given array of strings using strcmp function in C
A function that sorts given array of strings using strcmp function in C

Time:11-20

I've been trying to write a function named sort that takes function and its size as argument and sorts the array using bubble sort in C. But mine doesn't work most of the time. Here's the code:

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

void print(char a[][10], int size);
void sort(char a[][10], int size);

int main(){
    int n;
    scanf("%d", &n);
    char a[n][10];
    
    int i;
    for (i = 0; i < n; i  ){
        scanf("%s", a[i]);
    }
    
    print(a, n);
    sort(a, n);
    print(a, n);
}

void print(char a[][10], int size){
    int i;
    printf("\n");
    for(i = 0; i < size; i  ){
        printf("%s", a[i]);
        printf("\n");
    }
}

void sort(char a[][10], int size){
    int i, j;
    char temp[10];
    
    for(i = 0; i < size; i  ){
        for(j = 0; j < size - i - 1; j  ){
            if(strcmp(a[j], a[j   1]) > 0)
                strcpy(temp , a[j]);
                strcpy(a[j] , a[j   1]);
                strcpy(a[j   1], temp);     
        }
    }
}

Expected input: 3 man car dog

Expected output: car dog man

what I got: dog man man

The code I wrote above only works when the order is in reverse (man dog car). Please help.

CodePudding user response:

In this code snippet:

if(strcmp(a[j], a[j   1]) > 0)
    strcpy(temp , a[j]);
strcpy(a[j] , a[j   1]);
strcpy(a[j   1], temp);

You are missing curly-braces after the condition. It should be:

if(strcmp(a[j], a[j   1]) > 0) {
    strcpy(temp , a[j]);
    strcpy(a[j] , a[j   1]);
    strcpy(a[j   1], temp);
}
  • Related