1.
Introduction
2.
Problem statement
3.
Approach
4.
Code
5.
Complexity
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

# Sort the Given Array after Sorting Each Number Individually

Malay Gain
0 upvote

## Introduction

Sorting means ordering of given elements based on their priority to that context. By default, it means increasing order. In computer science, Sorting algorithms are very commonly used to solve DSA problems and implement algorithms. Sorting a number is also an interesting concept. We will see how both of these concepts will be used to solve this problem.

## Problem statement

You are given an array of integers. First, sort the integers individually and then sort the whole array.

Input:

arr[ ]={41, 54, 23, 100, 31};

Output:

ans[ ]={1, 13, 14, 23, 45}

Explanation

After sorting digits of the integers of the given array, resulted array will be

{14, 45, 23, 1, 13}. Now if we sort the resulting array, it will return {1, 13, 14, 23, 45}.

Note: Please try to solve the problem first and then see the solution below.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

## Approach

To sort the integers individually, we need to sort the digits of the integer. But to sort digits of the integer, convert the integer to a string and then sort the string. It will result in a sorted number.

After sorting each integer of the array, sort the array.

Output

## Complexity

The time complexity of the above implementation is O(nlogn) and space complexity is O(1).

Also see,  Rabin Karp Algorithm.

## FAQs

1. What is stoi() in C++?
stoi() takes a string as input and returns the corresponding integer value.

2. What is the difference between atoi() and stoi()?
atoi() and stoi() both functions work similarly but atoi() takes an array of characters as input and stoi() can be used for an array of characters as well as string class in C++.
atoi() is mostly used in the C programming language.

3. Which sorting algorithm is used to implement the STL sort() function?
It uses a hybrid algorithm of quick sort, heap sort, and insertion sort. But by default, it is Quicksort that takes  O(nlogn) in the worst case.

## Key Takeaways

This article covered how to sort the given array after sorting each number individually and implementing corresponding c++ code.