use*_*752 3 arrays sorting algorithm
给定一个数组,该数组具有递增顺序直到最大值然后按降序排列的数字.
Eg. int a[] = { 10, 12, 14, 16, 15, 13, 11}.
Run Code Online (Sandbox Code Playgroud)
如何有效地对这个数组进行排序?
数组需要就地排序.
我的解决方案
从数组和数组结束开始 2个指针.
进入结果数组,从两个指针写入一个min(或者如果你需要以降序排序,则为max),并将指针移动到1个位置(开始指针+1位置和结束指针-1位置)
重复直到开始指针将放在结束指针之后.
解的复杂性是O(N).所需内存为O(N)
伪代码:
function Sort(a)
{
startPointer = 0;
endPointer = a.length-1;
result = new Array of size a.length
while (startPointer <= endPointer)
{
var newValue;
if (a[startPointer] < a[endPointer])
{
newValue = a[startPointer];
startPointer +1
}
else
{
newValue = a[endPointer];
endPointer -1
}
result[a.length - startPointer - endPointer] = newValue;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
更新问题的解决方案:
作为解决方案,我们对数组的第一部分进行了部分排序.
指针(10和11){10,12,14,16,15,13,11}
指针(12和11)交换12和11 {10,11,14,16,15,13,12}
指针(14和12)交换14和12 {10,11,12,16,15,13,14} //将指针从14移动到13更小.
现在我们已经为{16,15,13,14}排序了{10,11,12}和子问题(子问题的N减少了两次)
该算法的复杂度为:O(N)+(N/2)+ O(N/4)+ ...总是O(N)
图为更好的插图:
