C - Sorting array strings with bubble sort

Introduction

Use the strcmp() function to compare strings to determine whether they need to be swapped.

Demo

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

int main()//from  ww w .  j  av a 2 s  .  c  o m
{
    char *fruit[] = {
        "watermelon",
        "banana",
        "pear",
        "apple",
        "coconut",
        "grape",
        "blueberry"
    };
    char *temp;
    int a,b,x;

    for(a=0;a<6;a++)
        for(b=a+1;b<7;b++)
            if(strcmp(*(fruit+a),*(fruit+b)) > 0 )
            {
                temp = *(fruit+a);
                *(fruit+a) = *(fruit+b);
                *(fruit+b) = temp;
            }

    for(x=0;x<7;x++)
        puts(fruit[x]);

    return(0);
}

Result

Related Topic