您的位置:首页 > 职场人生

这是一个我面试某公司的算法题目:对一个字符数组进行排序,根据给定的字符,大于它的,放在数组的左边,小于它的,放在数组的右边,且数组中的元素之间的相对位置要保持不变。

2013-01-24 11:46 781 查看
这个题目面试的时候,用的是最简单,但多开辟内存的方法,后来自己想想,在原数组进行操作的方法:

private static string GreaterLeftLessRight(string str, char c)
{
char[] array = str.ToCharArray();
int comparingIndex = str.IndexOf(c);
int i = 0;
int j = comparingIndex + 1;
int lastExchangePositionInLeft = -1;
int lastExchangePositionInRight = -1;
int rightestIndex = comparingIndex;
char tmp;
while (i < comparingIndex || j < array.Length)
{
int shouldExchangeInLeft = -1;
int shouldExchangeInRight = -1;
while (i < comparingIndex)
{
if (array[i] < c)
{
shouldExchangeInLeft = i;
i++;
break;
}
else
{
i++;
}
}
while (j < array.Length)
{
if (array[j] >= c)
{
shouldExchangeInRight = j;
j++;
break;
}
else
{
j++;
}
}
if (shouldExchangeInLeft != -1 && shouldExchangeInRight != -1 && array[shouldExchangeInRight] != c)
{
ExchangeCharacterInArray(array, shouldExchangeInLeft, shouldExchangeInRight);
lastExchangePositionInLeft = shouldExchangeInLeft;
lastExchangePositionInRight = shouldExchangeInRight;
}
else if (shouldExchangeInLeft != -1 && shouldExchangeInRight == -1)
{
tmp = array[shouldExchangeInLeft];
int moveEndIndex = lastExchangePositionInRight == -1 ? array.Length - 1 : lastExchangePositionInRight;
MoveCharacterInArray(array, shouldExchangeInLeft, moveEndIndex, tmp);
i--;
comparingIndex--;
}
else if (shouldExchangeInLeft != -1 && array[shouldExchangeInRight] == c)
{
array[shouldExchangeInRight] = array[shouldExchangeInLeft];
MoveCharacterInArray(array, shouldExchangeInLeft, rightestIndex, c);
i--;
comparingIndex--;
}
else if (shouldExchangeInLeft == -1 && shouldExchangeInRight != -1 && array[shouldExchangeInRight] != c)
{
tmp = array[shouldExchangeInRight];
MoveCharacterInArray(array, shouldExchangeInRight, comparingIndex, tmp);
comparingIndex++;
rightestIndex = comparingIndex;
}
else if (shouldExchangeInLeft == -1 && shouldExchangeInRight != -1 && array[shouldExchangeInRight] == c)
{
int moveEndIndex = rightestIndex + 1;
MoveCharacterInArray(array, shouldExchangeInRight, moveEndIndex, c);
rightestIndex = moveEndIndex;
}
}
return new string(array);
}

private static void MoveCharacterInArray(char[] array, int startIndex, int endIndex, char endCharacter)
{
if (startIndex == endIndex)
{
return;
}
else if (startIndex < endIndex)
{
for (int k = startIndex; k < endIndex; k++)
{
array[k] = array[k + 1];
}
array[endIndex] = endCharacter;
}
else
{
for (int k = startIndex; k > endIndex; k--)
{
array[k] = array[k - 1];
}
array[endIndex] = endCharacter;
}
}

private static void ExchangeCharacterInArray(char[] array, int leftPosition, int rightPosition)
{
char tmp = array[leftPosition];
array[leftPosition] = array[rightPosition];
array[rightPosition] = tmp;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐