Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a simpler way with a simpler notation to do the following part of code:

void swap(char **s1, char **s2){
    char *tmp=*s1;
    *s1=*s2;
    *s2=tmp;
}

void sort(char ***m, int dim){
    int i, j, flag=1;

    for(i=0; i<dim-1 && flag==1; i++){
        flag=0;
        for(j=0; j<dim-1; j++)
            if(strcmp((*m)[j],(*m)[j+1])>0){
                swap(&(*m)[j],&(*m)[j+1]);
                flag=1;
            }
    }
}

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

    char **m, s[30];
    int i;

    m=malloc(N*sizeof(char *));
    for(i=0; i<N; i++){
        scanf("%s", s);
        m[i]=strdup(s);
    }

    sort(&m, N);
    for(i=0; i<N; i++)
        printf("%s\n", m[i]);

    for(i=0; i<N; i++)
        free(m[i]);
    free(m);

    return 0;
}

The aim is to sort an array of strings allocated dynamically. What I've written above works but I want to know if there is a more efficient and readable way to write the function sort.

share|improve this question

migrated from stackoverflow.com Aug 12 at 12:07

This question came from our site for professional and enthusiast programmers.

up vote 1 down vote accepted

Assuming the logic of your sort code is correct.


You can just have your sort function as:

void sort(char **m, int dim);

Your sort function can be like:

void sort(char **m, int dim) {
    int i, j, flag=1;

    for(i=0; i<dim-1 && flag==1; i++){
        flag=0;
        for(j=0; j<dim-1; j++)
            if(strcmp(m[j],m[j+1])>0){
                swap(&m[j],&m[j+1]);
                flag=1;
            }
    }
}

This improves some readability. There is no need to pass &m - like (sort(&m, N)) - to your sort. Just passing m - like sort(m, N) - is enough for changing/comparing/swapping m[i] and m[j].

share|improve this answer
    
@Iu Tub Your code still can be improved performance wise. As you have written, it has O(n^2) worst case time complexity. You can make it nlog(n) if you write a merge sort, or nlog(n) in average case if you write quick sort. – sps Aug 5 at 15:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.