Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Sort an array of strings having characters at odd and even indices sorted in decreasing and increasing order respectively

  • Last Updated : 14 Jun, 2021

Given an array arr[] consisting of N strings, the task is to first sort the characters at odd and even indices of the string in decreasing and increasing order respectively, for each string of the array and then, sort the modified array.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {“ball”, “bat”, “boy”}
Output: albl atb byo
Explanation:
S[0]=”ball” is converted to “albl”
S[1]=”bat” is converted to “atb”
S[2]=”boy” is converted to “byo”
Sorted sequence of the modified array is: albl atb byo.



Input: arr[] = {“geeks”, “gfg”, “hello”, “world”}
Output: dwlro eohll esekg fgg

Approach: The given problem can be solved by traversing the given array arr[] of strings and for each string firstly sort the string and then rearrange each string such that characters at even indices are in ascending order and characters at odd indices are in descending order. In the end, sort the new array of strings in ascending order. Follow the steps below to solve the problem:

  • Traverse the given array of strings arr[] and for each string perform the following steps:
    • Sort the string arr[i] in alphabetical order.
    • Initialize a variable, say temp as “” that stores the resultant string.
    • Traverse the string arr[i] for the half-length of the string arr[i] and store the ith index from the start and the end of the string to the string temp.
    • If the size of the string is odd, then add the middle character of the string arr[i] to the end of the variable temp.
    • After the above steps, update the string at the ith index of the array arr[i] to the string temp.
  • After completing the above steps, sort the new array of strings in ascending order and print the array of strings arr[].

Below is the implementation of the above approach.

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort even indices in
// ascending order and odd indices in
// descending order and sort the array
// of strings in ascending order
void sortString(string S[], int N)
{
    // Traverse array of strings
    for (int i = 0; i < N; i++) {
 
        // Sort string in ascending order
        sort(S[i].begin(), S[i].end());
 
        // Length of string
        int n = S[i].size();
 
        string temp = "";
 
        // Traverse the string
        for (int j = 0; j < n / 2; j++) {
            temp += S[i][j];
            temp += S[i][n - j - 1];
        }
 
        // If length of string is odd
        if (n & 1)
            temp += S[i][n / 2];
 
        S[i] = temp;
    }
 
    // Sort array of strings
    sort(S, S + N);
 
    // Print array of strings
    for (int i = 0; i < N; i++) {
        cout << S[i] << " ";
    }
}
 
// Driver Code
int main()
{
    string arr[] = { "ball", "bat", "boy" };
    int N = sizeof(arr) / sizeof(arr[0]);
    sortString(arr, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
static String sortString(String inputString)
{
     
    // Convert input string to char array
    char tempArray[] = inputString.toCharArray();
       
    // Sort tempArray
    Arrays.sort(tempArray);
       
    // Return new sorted string
    return new String(tempArray);
}
 
// Function to sort even indices in
// ascending order and odd indices in
// descending order and sort the array
// of Strings in ascending order
static void sortString(String S[], int N)
{
     
    // Traverse array of Strings
    for(int i = 0; i < N; i++)
    {
         
        // Sort String in ascending order
        S[i] = sortString(S[i]);
 
        // Length of String
        int n = S[i].length();
 
        String temp = "";
 
        // Traverse the String
        for(int j = 0; j < n / 2; j++)
        {
            temp += S[i].charAt(j);
            temp += S[i].charAt(n - j - 1);
        }
 
        // If length of String is odd
        if (n %2== 1)
            temp += S[i].charAt(n / 2);
 
        S[i] = temp;
    }
 
    // Sort array of Strings
    Arrays.sort(S);
 
    // Print array of Strings
    for(int i = 0; i < N; i++)
    {
        System.out.print(S[i] + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    String arr[] = { "ball", "bat", "boy" };
    int N = arr.length;
     
    sortString(arr, N);
}
}
 
// This code is contributed by Amit Katiyar

Python3




# Python3 program for the above approach
 
# Function to sort even indices in
# ascending order and odd indices in
# descending order and sort the array
# of strings in ascending order
def sortString(S, N):
     
    # Traverse array of strings
    for i in range(N):
         
        # Sort string in ascending order
        S[i] = ''.join(sorted(S[i]))
 
        # Length of string
        n = len(S[i])
 
        temp = ""
 
        # Traverse the string
        for j in range(n // 2):
            temp += S[i][j]
            temp += S[i][n - j - 1]
 
        # If length of string is odd
        if (n & 1):
            temp += S[i][n // 2]
 
        S[i] = temp
 
    # Sort array of strings
    S.sort()
 
    # Print array of strings
    for i in range(N):
        print(S[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    arr = ["ball", "bat", "boy"]
    N = len(arr)
     
    sortString(arr, N)
 
# This code is contributed by ipg2016107

C#




// C# program for the above approach
using System;
 
public class GFG{
 
static String sortString(String inputString)
{
     
    // Convert input string to char array
    char []tempArray = inputString.ToCharArray();
       
    // Sort tempArray
    Array.Sort(tempArray);
       
    // Return new sorted string
    return new String(tempArray);
}
 
// Function to sort even indices in
// ascending order and odd indices in
// descending order and sort the array
// of Strings in ascending order
static void sortString(String []S, int N)
{
     
    // Traverse array of Strings
    for(int i = 0; i < N; i++)
    {
         
        // Sort String in ascending order
        S[i] = sortString(S[i]);
 
        // Length of String
        int n = S[i].Length;
 
        String temp = "";
 
        // Traverse the String
        for(int j = 0; j < n / 2; j++)
        {
            temp += S[i][j];
            temp += S[i][n - j - 1];
        }
 
        // If length of String is odd
        if (n %2== 1)
            temp += S[i][n / 2];
 
        S[i] = temp;
    }
 
    // Sort array of Strings
    Array.Sort(S);
 
    // Print array of Strings
    for(int i = 0; i < N; i++)
    {
        Console.Write(S[i] + " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    String []arr = { "ball", "bat", "boy" };
    int N = arr.Length;
     
    sortString(arr, N);
}
}
 
// This code is contributed by Amit Katiyar
Output: 
albl atb byo

 

Time Complexity: O(N*log N)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!