Alternate Lower Upper String Sort in C++

C++Server Side ProgrammingProgramming

A string is an array of characters. And this problem is to sort the elements of the string with alternate upper and lower case.

Problem Description − Alternate lower upper string sort, is a problem in which we are provided an unordered string which contains mixed upper and lowercase characters and we need to sort this string in such a way that upper and lower case characters are placed in alternate positions but are in a sorted manner.

Let’s take an example to understand the topic better,

Input : aFegrAfStRzsV
Output : AaFeRfSgVrstz
Explanation :
Upper case characters : A F R S V
Lower case characters : a e f g r s t z

Both are in a sorted manner so we can now place them in alternate order.

Now, since we have understood the problem. Let's create a solution for it. One way is creating arrays for both uppercase and lowercase letters in sorted order and then alternating them in the final string. We have created an algorithm based on this logic.

Algorithm

Step 1 : In an array lowercount[] add all lowercase characters in sorted order.
Step 2 : In an array uppercount[] add all uppercase characters in sorted order.
Step 3 : Create the final string using alternate values from both arrays.
Step 4 : Print the result array.

Example

 Live Demo

#include <iostream>
using namespace std;
#define MAX 26
void alternateULSort(string& s) ;
int main(){
   string str = "aFegrAfStRzsV";
   cout<<"The unsorted string is : "<<str;
   cout<<"\nThe alternate lower upper sorted string is ";
   alternateULSort(str);
   cout << str << "\n";
}
void alternateULSort(string& s){
   int n = s.length();
   int lowerCount[MAX] = { 0 }, upperCount[MAX] = { 0 };
   for (int i = 0; i < n; i++) {
      if (isupper(s[i]))
         upperCount[s[i] - 'A']++;
      else
         lowerCount[s[i] - 'a']++;
   }
   int i = 0, j = 0, k = 0;
   while (k < n) {
      while (i < MAX && upperCount[i] == 0)
         i++;
      if (i < MAX) {
         s[k++] = 'A' + i;
         upperCount[i]--;
         }
      while (j < MAX && lowerCount[j] == 0)
         j++;
      if (j < MAX) {
         s[k++] = 'a' + j;
         lowerCount[j]--;
      }
   }
}

Output

The unsorted string is : aFegrAfStRzsV
The alternate lower upper sorted string is AaFeRfSgVrstz
raja
Published on 16-Oct-2019 07:33:34
Advertisements