Search code examples
carrayssortingbubble-sort

Trying to write a C program to bubble sort 25 words from a 2 dimensional array alphabetically


I figured out how to read in the strings, but I'm not sure how to use bubble sort to arrange them alphabetically. This is what I have to far. I keep receiving the error "Segmentation fault (core dumped).

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

#define NUM 25   /* number of strings */
#define LEN 1000  /* max length of each string */

     main()
        {
          char Strings[NUM][LEN];
          int i, j;
          char tempValue;

          printf("Please enter %d strings, one per line:\n", NUM);

          for(i=0; i<NUM-1; i++)
          {    
           fgets(Strings[i], LEN-2, stdin);
          }

          for(i=0; i<NUM-1; i++)
          {
            for(j=0; j<LEN-2; j++)
            {
              if(Strings[i][j] < Strings[i+1][j]) 
              {
                tempValue = Strings[i][j];
                Strings[i][j] = Strings[i + 1][j];
                Strings[i + 1][j] = tempValue;


              }
            }
          }

        }

Solution

  • Use strcmp

    if(strcmp(Strings[i], Strings[i+1]) > 0) 
    {
        //swap elements
    }
    

    it will basically compare chars in strings and first not matching pair of chars, if it has greater value in first string passed to function, it will return 1.