划分一个整形数组,把负数放在左边,零放在中间,正数放在右边

题目:划分一个整形数组,把负数放在左边,零放在中间,正数放在右边

思路:扫描遍历,发现正数出现在负数前面,就调换位置。

代码:

    public static int[] arrayChange(int[] array) {
        int length = array.length;
        int low = 0;
        int high = length - 1;

        // 扫描遍历,发现正数出现在负数前面,就调换位置
        while (low < high) {
            while (array[low] < 0 && low < high) {
                low++;
            }
            while (array[high] > 0 && low < high) {
                high--;
            }
            int temp = array[low];
            array[low] = array[high];
            array[high] = temp;
        }
        return array;
    }

本文永久更新地址:https://github.com/nnngu/LearningNotes/blob/master/_posts/2018-03-17-%E5%88%92%E5%88%86%E4%B8%80%E4%B8%AA%E6%95%B4%E5%BD%A2%E6%95%B0%E7%BB%84%EF%BC%8C%E6%8A%8A%E8%B4%9F%E6%95%B0%E6%94%BE%E5%9C%A8%E5%B7%A6%E8%BE%B9%EF%BC%8C%E9%9B%B6%E6%94%BE%E5%9C%A8%E4%B8%AD%E9%97%B4%EF%BC%8C%E6%AD%A3%E6%95%B0%E6%94%BE%E5%9C%A8%E5%8F%B3%E8%BE%B9.md