Home > Software engineering >  Order lists of words alphabetically using insertion sort
Order lists of words alphabetically using insertion sort

Time:11-07

I am a student of Computer Science and I have to order a list of words using the insertion sort. I tried to adapt the insertion sort for numbers but apparently my code is ordering only the first letter of each word. Can I have some thoughts from you on how can I solve this problem.

NOTE: Consider the order A>B>C>....>Z>a>b>c>.....>z

#include <stdio.h>
#include <stdlib.h>


void insertionSort (char **words, int n) {
    int i, j;
    char key;
    /* a cada iteração, teremos o vetor A[1..i] ordenado */
    /* começamos de A[i], porque obviamente o vetor em A[0..0] está 
        trivialmente ordenado */

    for(i=1;i<n;i  ){
        key=words[i][0];
        j=i-1;
        while(j>=0 && words[j][0]>key){
            words[j 1][0]=words[j][0];
            j=j-1;
        }
        words[j 1][0]=key;
    }
}


int main() {
    int i, n;
    char **words;

    printf("Insert the number of words: \n");
    scanf("%d", &n);

    words=malloc(n*sizeof(char*));
    for(i=0;i<n;i  ){
        words[i]=malloc(10*sizeof(char));
    }

    for(i=0;i<n;i  ){
        scanf("%s", words[i]);
    }
    insertionSort(words,n);
    for(i=0;i<n;i  ){
        printf("%s", words[i]);
        printf("\n");
    }

    for(i=0;i<n;i  ){
        free(words[i]);
    }
    free(words);

  return 0;
}

Exemple
./insertion
Insert the number of words:
5
grey
blue
white
green
red

I get this as an output:
brey
glue
ghite
rreen
wed

But I want this:
blue
green
grey
red
white

CodePudding user response:

You have a mistakes in your algorithm.

Instead of comparing strings you compare first characters of the strings. That's because you use words[idx][0] all over the code. Instead you should use strcmp() function from string.h to compare the strings.

Then insertionSort function would look like that:

void insertionSort(char **words, int n) {
    int i, j;
    char *key;

    for (i = 1; i < n; i  ) {
        key = words[i];
        j = i - 1;
        while (j >= 0 && strcmp(words[j], key) > 0) {
            words[j   1] = words[j];
            j = j - 1;
        }
        words[j   1] = key;
    }
}
  • Related