HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Sorting strings in a one dimensional array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortingarrayonedimensionalstrings

Problem

What are the better solutions possible?

I have a character array with different strings. There is a max size for the strings. In case a string is smaller than max size remaining places are filled with '-'.
Sorting has to be done on this.


Example:


maxStringSize = 5


totalStrings = 4


InputArray: w,a,t,e,r, c,a,t,-,-, f,i,v,e,-, b,a,l,l,-,-


outputArray: b,a,l,l,-,-, c,a,t,-,-, f,i,v,e,-, w,a,t,e,r

-

public class QuestionOne {

char[] mInput = {'w','a','t','e','r','c','a','t','-','-','f','i','v','e','-','b','a','l','l','-','-'};
int mBlockSize = 5;
int mTotalBlocks = 4;

public void init(char[] input, int blockSize, int totalBlocks)
{
    mInput = input;
    mBlockSize = blockSize;
    mTotalBlocks = totalBlocks;
}

public char[] sort()
{

    for(int i=0; i mInput[j*mBlockSize+count])
                {
                    swapBlocks(i,j);
                    break;
                }
                else if(mInput[i*mBlockSize+count]<mInput[j*mBlockSize+count])
                    break;
            }
        }
    }
    return mInput;
}

private void swapBlocks(int blockOne, int blockTwo)
{
    for(int i=0; i<mBlockSize; i++)
    {
        swap(blockOne*mBlockSize+i,blockTwo*mBlockSize+i);
    }
}

private void swap(int one, int two)
{
    char temp = mInput[one];
    mInput[one] = mInput[two];
    mInput[two] = temp;
}

}


What are the better solutions possible?

Solution

How about the simple process of converting the chars to separate strings, sorting the Strings, then copying the results back to an array?

It would look something like:

String source = new String(input);
String[] values = new String[input.length / blocksize];
for (int i = 0; i < values.length; i++) {
    values[i] = source.substring(i * blocksize, (i + 1) * blocksize);
}
Arrays.sort(values);
char[] result = new char[values.length * blocksize];
for (int i = 0; i < values.length; i++) {
    System.arraycopy(values[i].toCharArray(), 0, result, i* blocksize, blocksize);
}
return result;

Code Snippets

String source = new String(input);
String[] values = new String[input.length / blocksize];
for (int i = 0; i < values.length; i++) {
    values[i] = source.substring(i * blocksize, (i + 1) * blocksize);
}
Arrays.sort(values);
char[] result = new char[values.length * blocksize];
for (int i = 0; i < values.length; i++) {
    System.arraycopy(values[i].toCharArray(), 0, result, i* blocksize, blocksize);
}
return result;

Context

StackExchange Code Review Q#37140, answer score: 4

Revisions (0)

No revisions yet.