这道题是否会让你想起快速排序中的分裂操作?只不过快速排序分开的标准是分大小分别存放而已。
//左偶右奇
void apartEvenOdd(ElemType Buff[],UINT32 len)
{
ElemType temp;
int head=0,tail = len-1;
while (head<tail)
{
//寻找奇数
if(Buff[head]%2==0)
{
head++;
}
//寻找偶数
if(Buff[head]%2==1)
{
tail--;
}
if (head<tail)
{
//交换两个的顺序
temp = Buff[head];
Buff[head] = Buff[tail];
Buff[tail] = temp;
}
}
}
python实现:
@print_result_after
def partition_even_odd(data):
start = 0
last = len(data) - 1
while start <= last and is_even(data[start]):
start += 1
pivot = data[start]
while start < last:
while start < last:
if is_even(data[last]):
data[start] = data[last]
start += 1
break
else:
last -= 1
while start < last:
if not is_even(data[start]):
data[last] = data[start]
last -= 1
break
else:
start += 1
data[start] = pivot
return data
def main():
data = [3,0,1,2,4,5,6]
partition_even_odd(data)