Wap to sort a list of names in the ascending order of length of the names

C program to sort names in alphabetical order

CServer Side ProgrammingProgramming

User has to enter number of names, and those names are required to be sorted in alphabetical order with the help of strcpy[] function.

An array of characters [or] collection of characters is called a string.

Python | Sort a List according to the Length of the Elements

In this program, we need to accept a list and sort it based on the length of the elements present within.
Examples:

Input : list = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"] Output : ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad'] Input : list = [["ram", "mohan", "aman"], ["gaurav"], ["amy", "sima", "ankita", "rinku"]] Output : [['gaurav'], ['ram', 'mohan', 'aman'], ['amy', 'sima', 'ankita', 'rinku']] Note: The first example comprises of Strings whose length can be calculated. The second example comprises of sublists, which is also arranged according to there length.

Sort an array of strings according to string lengths

We are given an array of strings, we need to sort the array in increasing order of string lengths.
Examples:

Input : {"GeeksforGeeeks", "I", "from", "am"} Output : I am from GeeksforGeeks Input : {"You", "are", "beautiful", "looking"} Output : You are looking beautiful
Recommended: Please try your approach on {IDE} first, before moving on to the solution.

A simple solution is to write our own sort function that compares string lengths to decide which string should come first. Below is the implementation that uses Insertion Sort to sort the array.

C++




// C++ program to sort an Array of
// Strings according to their lengths
#include
using namespace std;
// Function to print the sorted array of string
void printArraystring[string,int];
// Function to Sort the array of string
// according to lengths. This function
// implements Insertion Sort.
void sort[string s[], int n]
{
for [int i=1 ;i= 0 && temp.length[] < s[j].length[]]
{
s[j+1] = s[j];
j--;
}
s[j+1] = temp;
}
}
// Function to print the sorted array of string
void printArraystring[string str[], int n]
{
for [int i=0; i

Bài mới nhất

Chủ Đề