Sort even indices digits in ascending order and odd indices digits in descending order

By | October 3, 2023

Given a number num (0 < num < 108), the task is to sort the digits of the number such that even indices are in ascending order and odd indices in descending order.

Examples:

Input: num = 1423
Output: 4132
Explanation:
Sort number num in ascending order: num = 1234
Replace even indices in ascensing order: *1*2
And odd indices in descending order: 4*3*
So the becomes 4132.

Input: num = 500100
Output: 501000

RECOMMENDED: Characteristics or features of an Algorithm

Approach:

Follow the steps below to solve the problem:

  • Convert the number to a string.
  • Sort the string in alphabetical order.
  • Traverse the string for half-length and at each iteration print last ith index and ith index of the string.
  • If the size of the string is odd, after completion of iteration print the middle character of the string.

Below is the implementation of the above approach.

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to sort odd indices in ascending order and even
// indices in descending order of the number
void sortNum(int num)
{
    // Converting number to string
    string S = to_string(num);

    // Length of string
    int n = S.size();

    // Sort string in ascending order
    sort(S.begin(), S.end());

    // Traverse the string
    for (int i = 0; i < n / 2; i++) {
        cout << S[n - i - 1] << S[i];
    }

    // If length of string is odd
    if (n & 1)
        cout << S[n / 2];
}

// Driver Code
int main()
{
    int num = 1423;
    sortNum(num);

    return 0;
}

Output: 

4132

Time Complexity: O(|num|)
Auxiliary Space: O(1)

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.