数组正负元素前后移动算法的实现(以0为分界线)

package test;


/**
 * 数组正负元素前后移动算法的实现(以0为分界线,可以为其他任意一个数)
 * 负数前移,放在数组前面部分,正数放在后面
 * @author hao
 *
 */
public class MoveNumTest {


/**
* @param args
*/
public static void main(String[] args) {
int[] nums = {342,6,3453645,-324, 1, 6, -4, 645, -3534, 34, -3, 345, 98956,-6 };
MoveNumTest test = new MoveNumTest();
test.movenum1(nums);
test.movenum2(nums);
}

private void movenum2(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int tmpLeft = 0;
for (; left < right; left++) {
if (nums[left] > 0) {
tmpLeft = nums[left];
break;
}
}
if (tmpLeft != 0) {
for (; right > left; right--) {
if (nums[right] < 0) {
nums[left] = nums[right];
nums[right] = tmpLeft;
break;
}
}
}
}


System.out.println("\nleft= " + left + ", right= " + right);
for (int i : nums) {
System.out.print(i + " ");
}
}


private void movenum1(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int tmpLeft = 0;
for (; left < right; left++) {
if (nums[left] > 0) {
tmpLeft = nums[left];
break;
}
}
int tmpRight = 0;
for (; right > left; right--) {
if (nums[right] < 0) {
tmpRight = nums[right];
break;
}
}
if (tmpLeft != 0 && tmpRight != 0) {
nums[left] = tmpRight;
nums[right] = tmpLeft;
}
}


System.out.println("left= " + left + ", right= " + right);
for (int i : nums) {
System.out.print(i + " ");
}
}
}

你可能感兴趣的:(java,算法,android)