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

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.