1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Sort 5 Country Name

Discussion in 'C' started by scorpio, Jun 23, 2011.

  1. scorpio

    scorpio New Member

    Joined:
    Jun 21, 2011
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Hey!
    plz send me code for this
    Take 5 country names in an array as input and create a function which will sort that country names in alphabetical order.:)
     
  2. DRK

    DRK New Member

    Joined:
    Apr 13, 2012
    Messages:
    44
    Likes Received:
    3
    Trophy Points:
    0
    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define countryNo 5
    #define maxLength 100
    
    void sortNames(char country[countryNo][maxLength])
    {
    	char temp[maxLength];
    	int i, j;
    
    	// [URL=http://www.go4expert.com/articles/bubble-sort-algorithm-absolute-beginners-t27883/]bubble sort[/URL]
    	for (j = 0; j < countryNo - 1; j++)
    	{
    		for (i = 0; i < countryNo - 1; i++)
    		{
    			if (strcmp(country[i], country[i + 1]) > 0)
    			{
    				strcpy(temp, country[i]);
    				strcpy(country[i], country[i + 1]);
    				strcpy(country[i + 1], temp);
    			}
    		}
    	}
    }
    
    
    int main(int argc, char **argv)
    {
    	char country[countryNo][maxLength];
    	int i;
    
    	// enter names
    	for (i = 0; i < countryNo; i++)
    	{
    		printf("Enter name of country #%d: ", i + 1);
    		gets(country[i]);
    	}
    
    	sortNames(country);
    
    	// display
    	for (i = 0; i < countryNo; i++)
    	{
    		printf("%s\n", country[i]);
    	}
    
    	return 0;
    }
     

Share This Page