C++ Program To Sort Words In Alphabetic Order

What we are going to see through this article is we will see in detail C++ Program To Sort Words In Alphabetic Order. Arranging or arranging a group of characters in a particular order, that is, ascending or descending based on their ASCII values, is called sorting a string. The output of the sorting scheme generates the rearranged input or its permutation.

For example, consider the following strings

Input: face

Output: acef

Input: focus

Output: cfosu

C++ Program To Sort Words In Alphabetic Order

C++ Program to Sort Words in Alphabetic Order

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

//function to print the array
void print(vector<string> names){
	printf("printing ........\n");
	for(int i=0;i<names.size();i++)
		cout<<names[i]<<endl;
	printf("\n");
}

bool mycomp(string a, string b){
	//returns 1 if string a is alphabetically 
	//less than string b
	//quite similar to strcmp operation
	return a<b;
}

vector<string> alphabaticallySort(vector<string> a){
	int n=a.size();
	//mycomp function is the defined function which 
	//sorts the strings in alphabatical order
	sort(a.begin(),a.end(),mycomp);
	return a;
}

int main()
{   
	int n;
	printf("enter number of names to be added: ");
	scanf("%d",&n);

	//creating a vector of strings
	//vector to store strings(names)
	vector<string> names;
	string name;
	printf("enter names: \n");
	//taking input
	for(int i=0;i<n;i++){
		cin>>name;
		//insert names into the vector
		names.push_back(name); 
	}

	printf("\nbefore sorting\n");
	print(names);

	//function to sort names alphabetically
	names=alphabaticallySort(names);

	printf("after alphabetical sorting\n");
	print(names);

	return 0;
}

Output

enter number of names to be added: 5
enter names:
rahul
virat
vijay
bumrah
rahane

before sorting
printing ........
rahul
virat
vijay
bumrah
rahane

after alphabetical sorting
printing ........
bumrah
rahane
rahul
vijay
virat

Read Also: C++ Program To Calculate Simple Interest

Final Words

What we learned through this article is to C++ Program To Sort Words In Alphabetic Order. Also if you have any doubts please leave a comment via the comment box. And we ask that you benefit everyone who shared this article with your friends.

Leave a Comment