Bubble sort is a simple sorting algorithm, it compares each pair of adjacent items and swaps them if they are in the wrong order, this passes must be repeated until no swaps are needed, for more detail: Click here


/*
    compare two string itemF with itemL
    INPUT:
            itemF
            itemL
            descending  0 ascending 1 descending
    retutn  1 swappwd      
*/
char SwapItem(char* itemF,char* itemL, char descending)
{
    char *temps;
    char swapped=0;

    int compare=strcmp(itemF,itemL);
    temps=malloc(strlen(itemF)+1);
    if(compare!=0)
    {
        if(compare<0 && descending || compare>0 && !descending)
        {
            strcpy(temps,itemF);
            strcpy(itemF,itemL);
            strcpy(itemL,temps);
            swapped=1;
        }
    }
    else
        swapped=-1;

    free(temps);
    return swapped;
}
/*
    listof : Array of string to reorder
    Order  : 0 ascending 1 descending
    Count  : mumber of item to order
    return : number of swipes
*/
int OrderByBS(char** listof,char Order,int Count)
{
    int i,countswap=0,loops=0;
    char swapped=1,ordernow=1;
    int minval=-1;
    int maxval=-1,start=0;
    printf("\n");
    while(ordernow)
    {
        ordernow=0;
        for (i=start;i<Count-1;i++)
        {
            swapped=SwapItem(listof[i],listof[i+1],Order);
            if (swapped)
            {
                ordernow=1;
                countswap++;
            }
            loops++;
        }
        Count--;//new end for

    }
    return countswap;
}

How to use:

#define MAXROW 9
#define MAXCOL 50
#define ASCENDING 0
#define DESCENDING 1
char TestBubbleSort()
{
    char listof[MAXROW][MAXCOL];//declare array of string
    char *p[MAXROW];//pointer to array of string
    int i,countswap=0;


    printf("Load a list Of Strings\n");
    for (i=0;i<MAXROW;i++)
    {
        p[i]=listof[i];//pointing to string
        sprintf(p[i],"Item %c",i+i%6+65+(i&4));//print same text
        printf("%s\n",p[i]);//show

    }
   countswap=OrderByBS(&p,DESCENDING,MAXROW);//oreder by ascending
   printf("\n\nList Order by DESCENDING %d swipes\n",countswap);
    for (i=0;i<MAXROW;i++)
        printf("%s\n",p[i]);

   countswap=OrderByBS(&p,ASCENDING,MAXROW);//oreder by ascending
   printf("\n\nList Order by ASCENDING %d swipes\n",countswap);
    for (i=0;i<MAXROW;i++)
        printf("%s\n",p[i]);

}

this is result:
orderby

See also:Array of Strings

Advertisements