Friday, December 19, 2014

Lexicographic sorting of strings

/* Program to perform lexicographic sorting of strings */


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

void main()
{
  char str[50][50], temp[50], str1[50][50], n[1], temp1[50];
  int i, j, m, k;
  printf("\n##############################\n");
  printf("Enter the number of strings\n");
  gets(n);
  m = atoi(n);
  printf("\n##############################\n");
  printf("Enter the strings\n");
  for(i = 0; i < m; i++)
    gets(str[i]);

  // Convert all letters to lowercase
  for(i = 0; i < m; i++)
    for(j = 0; j < strlen(str[i]); j++)
      if(isupper(str[i][j]) != 0)
        str1[i][j] = tolower(str[i][j]);
      else
        str1[i][j] = str[i][j];

  for(i = 0; i < m; i++)
    for(j = i + 1; j < m; j++)
      if((strcmp(str1[i], str1[j])) > 0)
      {
        strcpy(temp, str[i]);strcpy(temp1, str1[i]);
        strcpy(str[i], str[j]);strcpy(str1[i], str1[j]);
        strcpy(str[j], temp);strcpy(str1[j], temp1);
      }

  printf("\n##############################\n");
  printf("Sorted list is \n");
  for(i = 0; i < m; i++)
    puts(str[i]);
  printf("##############################\n");
}


Written by

No comments:

Post a Comment