刷题看到这样一道题,以前都会上网找别人的思路,现在尝试自己思考分析。
解决思路:
从左遍历数组,找到第一个为负数的元素,从右向左找到第一个为正数的元素,交换。其中需要维护一个end变量记录右边位置,需要注意的是,end必须大于i。代码如下:
/**
* 将数组中正负数调整到各自一边
*/
public class ArithmerticPractice_12 {
public static int[] date = new int[]{1, -1, 4,-1,-2,-3,-5};
public static void adjust() {
//长度为0 1 2不需要调整
if (date.length <=2) {
return;
}
int length = date.length;
int end = length - 1;
for (int i = 0; i < length / 2 + 1; i++) {
if (date[i] < 0) {
//找到右边第一个负数并且需要i<end
while (date[end] < 0 && i<end) {
end--;
}
//交换
int temp = date[i];
date[i] = date[end];
date[end] = temp;
}
}
}
public static void main(String[] args) {
adjust();
System.out.println("result:" + Arrays.toString(date));
}
}