Search code examples
carrayscomputer-sciencebubble-sortc-strings

How do I output a bubble sorted 2-D string array in C?


How do I go about sorting a 2-D string array in C using bubble sort (or any other kind of sorting in that matter) ? What I'm actlly trying to do is as follows :

Example:

Unsorted 2-D string array :

abfg 
abcd 
xyzw 
pqrs 
orde

Sorted 2-D string array:

abcd 
abfg 
orde 
pqrs 
xyzw

My current algorithm which is not working (gives me an incompatibility error) is as follows :

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



int main()
{
    char str[5][4];
    int i,j;
    char temp[4];
    for (i=0;i<5;i++)
    {
        scanf("%s",str[i]);

    }


   for(i = 0; i<5-1; i++) 
   { 
     for(j = 0; j<5-1; j++) 
     {
         if(strcmp(str[j],str[j+1])== -1) 
        { 
            temp = str[j]; 
            str[j] = str[j+1]; 
            str[j+1] = temp; 
         }

     } 
   } 

   for(i = 0; i< 5; i++) 
     printf("%s ", str[i]);


    return 0;
}

Solution

  • Arrays are not assignable as you're attempting in C. You need to setup some buffer swapping logic. For example.

    if(strcmp(str[j+1],str[j]) < 0) // note: fixed. 
    {
        strcpy(temp, str[j]);
        strcpy(str[j], str[j+1]);
        strcpy(str[j+1], temp);
    }            
    

    Other issues with your code:

    • Incorrect size of your input array. All those strings require at least char[5] to hold four-char strings (including space for the terminator).
    • You do not length-restrict your input string length. For an array of four chars the format string should be "%3s", which would have hinted your dimensions were too short to begin with.
    • You do not validate the input succeeded by checking the result of scanf
    • Related to the above, you do know track how many successful inputs were achieved, therefore you don't know whether your sorting data against indeterminate garbage. If you only input 3 strings successfully, sorting an array of 5 strings is senseless.
    • Your bubblesort is not implemented correctly. Real bubblesort includes swap-detection which stops the sorting algorithm after any given pass results in no-swaps. You also are not reducing the number of elements scanned with each iteration by one, which is somewhat the point of bubblesort in the first place.

    Anyway, all of that is related to your code, but not the question you posted. It is worth looking at regardless.

    Best of luck.