Sort elements in Lexicographical Order in C

Sort elements in Lexicographical Order

We will write a program to sort elements in Lexicographical Order in C.This will help to understand the basic structure of programming. In this program , we will learn how to sort the elements in lexicographical order i.e. order in the dictionary.

sort elements in lexicographical order in c

Sort in Lexicographical Order:

Lexicographical Order can be understood as the order of alphabets we witness in a dictionary i.e. similar to the traditional alphabetical order we learn since our childhood.

We will write a C program to sort elements in lexical order (dictionary order). For this task, we will use strcmp() and strcpy() functions defined under <string.h>.

The strcmp() function used to compare two strings.

The strcpy() function is used to copy the string.

 

Example to sort the elements in lexical order:

Run

#include<stdio.h>
#include<string.h>
int main ()
{
  char str[5][50], temp[50];
  printf ("Enter 5 words: ");
  for (int i = 0; i < 5; ++i)
    {
      fgets (str[i], sizeof (str[i]), stdin);
    }
  for (int i = 0; i < 5; ++i)
    {
      for (int j = i + 1; j < 5; ++j) { if (strcmp (str[i], str[j]) > 0)
	    {
	      strcpy (temp, str[i]);
	      strcpy (str[i], str[j]);
	      strcpy (str[j], temp);
	    }
	}
    }

  printf ("\nIn the lexicographical order: \n");
  for (int i = 0; i < 5; ++i)
    {
      fputs (str[i], stdout);
    }
  return 0;
}

Input

Enter 5 words: R programming
JavaScript
Java
C programming
C++ programming

Output

In the lexicographical order:
C programming
C++ programming
Java
JavaScript
R programming

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription