C++ program to arrange names in alphabetical order

This is a simple program regarding strings in C++. The main objective of this is to sort the Strings in a dictionary or alphabetical order. In order to achieve this, we will have to take the first letter of every word and compare them. If the first letter comes to be the same then we will check and compare the next letter and so on.

Thankfully we don’t have to check the letters of the words one by one. There is a function known as “strcmp”. We are going to use that. This function compares the strings alphabetical value and returns the difference between them.

Illustration

Input: Aashish Sanjana Jolly Ashutosh Varun Parveen

Output: Aashish Ashutosh Jolly Parveen Sanjana Varun

This feat can be easily achieved by using the program given below. Please note that the names should b stored in a two-dimensional character array. We will be using ” Bubble Sorting” algorithm to sort the names. This is very much similar to the sorting of normal integer matrix, we will just be using the ASCII value of the letters to determine their index.

Algorithm of the code

  1. First, take input in a 2nd dimension character matrix.
  2. Traverse the inserted matrix using bubble sort technique.
  3. Compare the words using strcmp to compare the ASCII values of the words.
  4. If the greater word is in front then interchange using a third array and strcpy.
  5. Repeat this process for the entire array.

Program of the above code

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
  char names[10][10], temp[10];      //creating two character arrays, one for storing and one for interchanging
  int i, j;
  cout<<"Enter any 10 names  : ";
  for(i=0; i<10; i++)
  {
    cin>>names[i];
  }
  for(i=10; i>=0; i--)                 //bubble sort begins to sort the data 
  {
    for(j=0; j<=i; j++)
    {
      if(strcmp(names[j], names[j+1])>0)       //comparing only the ASCII equivalent of the entire word and interchanging if greater
      {
        strcpy(temp, names[j]);
        strcpy(names[j], names[j+1]);
        strcpy(names[j+1], temp);
      }
    }
  }
  cout<<"Names rearranged in alphabetical order : \n";
  for(i=0; i<10; i++)
  {
    cout<<names[i]<<"\n";
  }
  return 0;
}

 

Leave a Reply

Your email address will not be published.