C++ program to sort an array of strings alphabetically

In this tutorial, we are going to learn to sort an array of strings given in C++ in alphabetical order.MOSTLY, we need to sort the array of strings in lexicographical order(in alphabetical order). For example, if we are writing code for a college system. We need this because we need to sort the name of students in a lexicographical order for attendance and simplified system.

How to sort an array of strings alphabetically in C++

In this tutorial, we will learn the use of comparators and sort functions. As we know, Sort is a generic function in the C++ standard library for doing comparison sorting.It is predefined in #include<algorithm> header file . We will take the input of strings in an array. Secondly, we will pass that array in sort function as an argument. Moreover, we will learn below how to use comparators with our sort function below in different ways.

sort(array,array+n, comparator)

It takes 3 arguments :

  • array
  • array+(length of the array)
  • comparator

COMPARATORS AND HOW TO USE THEM IN DIFFERENT WAYS?

A Comparator is needed as a third argument in sort function to specify the order in which array is to be sorted.  A comparator always has a return type bool and always takes two arguments.

If we have to sort it in ascending order, we will use the below format:

bool comparator(string a,string b)
{
    return a<b;
}

Sorting in descending order:

bool comparator(string a,string b)
{
    return a>b;
}

Using a pre-defined comparator(sorting in descending order)

#include<bits/stdc++.h>
 using namespace std;
 
int main() 
{
  int n=5;
  string arr[]={"sandwich","apple","banana","zombie","pear"}; 
  sort(arr,arr+n,greater<int>()); 
  for(int i=0;i<n;i++)
 { cout<<arr[i]<<" "; 
 } 
}

Output:

zombie sandwich pear banana apple

NOTE:

  1. The sort function makes changes in the original array only.
  2.  When we do not pass any third argument then by default it gets sorted in ascending order.

We are using a user-defined comparator here. Here is the code for sorting an array of strings in lexicographical order.

#include<bits/stdc++.h>
using namespace std;

bool comparator(string a,string b)
{
    return a<b;
}

int main()
{
    int n=5;
    string arr[]={"sandwich","apple","banana","zombie","pear"};

    sort(arr,arr+n,comparator);

       for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }

}

Output :

apple banana pear sandwich zombie

 

Read more about sorting using different algorithms:

Leave a Reply

Your email address will not be published. Required fields are marked *