Skip to content

Latest commit

 

History

History
58 lines (44 loc) · 1.49 KB

20200903.md

File metadata and controls

58 lines (44 loc) · 1.49 KB

Algorithm

剑指Offer-调整数组顺序使奇数位于偶数前面

Description

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

Solution

public class Solution {
    public void reOrderArray(int [] array) {
        if (array == null || array.length == 0) {
            return;
        }
        int i = 0, j = 1;
        while (i < array.length) {
            //找到第一个偶数
            while (i < array.length && array[i] % 2 != 0) {
                i++;
            }
            j = i + 1;
            //找到第一个奇数
            while (j < array.length && array[j] % 2 == 0) {
                j++;
            }
            if (j < array.length) {
                int temp = array[j];
                for (int j2 = j - 1; j2 >= i; j2--) {
                    array[j2 + 1] = array[j2];
                }
                array[i] = temp;
                i++;
            } else {
                break;
            }
        }
    }
}

Discuss

相对位置不变--->保持稳定性;奇数位于前面,偶数位于后面 --->存在判断,挪动元素位置;

  1. 找到偶数
  2. 找到奇数
  3. 插入排序

Review

Tip

Share