1

Input: BDCAbaxz

OUTPUT: AaBbCDxz

My solution is straight forward and ugly:

  1. Sort the input with quick sort, then we get "ABCDabxz"

  2. Alloc a temp array with the same size as the original one, then take the appropriate element from two sub-array(ptr1-->A, ptr2--->a)

  3. Copy the temp array back to the original one

Any faster algorithm on this problem?

2 Answers 2

7

Yes.

Define a comparator for qsort that gives you the ordering you want in the first place (so rather than using AB...YZab...yz as the sort order, have it enforce AaBb...YyZz).

Sign up to request clarification or add additional context in comments.

2 Comments

@Paul: stricmp sorts strings, not characters. And it considers 'A' and 'a' as identical, which wouldn't give the OP the desired behaviour.
Oh yes - sorry - haven't woken up properly yet today... ;-)
5

If the input is long ( >> 255) you could make a counting sort.

char chars[256]; zeroed
while( *input)  // zero termination
    chars[*input++]++;

And extract it like

int pos = 0;
for(int i = 'A'; i<= 'Z'; i++)
{
    while( chars[i]-- ) 
        output(pos++] = (char)i;
    while( chars[i+'a'-'A']-- )
        output(pos++] = (char)i+'a'-'A';
}

O(N)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.