给定一个数组,有正数,负数和零,排列给定的数组,使负数在左边,0在中间,正数在右边。
Given an array with positive, negative and zeros, arrange the given array such that negatives are on left, zeros in the middle and positives on the right.
这个问题可以用荷兰国旗问题来解决。
用负数代替0,0代替1,正数代替2
This problem can be solved by modified Dutch National Flag problem.
Instead of '0' we have -ve numbers
Instead of '1' we have 0's(zero).
and for 2 we have +ve Numbers.
void swap(int * a,int * b){
int c;
c = *a;
*a = *b;
*b = c;
}
void sortNumbers(int *arr,int len)
{
int low = 0,mid = 0,high = len - 1;
while (mid <= high)
{
if (arr[mid] < 0 )
{
swap(&arr[low++],&arr[mid++]);
}
else
if (arr[mid] == 0)
{
mid++;
}
else
swap(arr[mid],arr[high--]);
}
}
本文介绍了一种使用荷兰国旗问题的修改版来解决数组中负数、零和正数的排序问题的方法。通过将数组中的元素分为三个类别,并利用三指针技术实现原地排序。
4694

被折叠的 条评论
为什么被折叠?



