21调整数组顺序使奇数位于偶数前

package sort;

public class Test21 {
    static int[] s = { 1, 3, 10, 5, 7, 9, 2, 4, 6, 8, 10 };

    public static void main(String[] args) {
        resot(s);
        for (int i : s) {
            System.out.println(i);

        }
    }

    public static int[] resot(int[] s) {//其实就是快排单次循环

        int low = 0;
        int high = s.length - 1;
        while (low < high) {  //快排使用while单次循环
            while (low < high && s[high] % 2 == 0) {//从后往前找奇数
                high--;
            }
            
            while (low < high && s[low] % 2 == 1) {//从前往后找偶数
                low++;
            }
            
            if (low < high) { //如果没有到达边界则交换奇数和偶数,继续while
                int temp = s[low];
                s[low] = s[high];
                s[high] = temp;

            }
        }

        return s;

    }
}
 

发布了41 篇原创文章 · 获赞 1 · 访问量 772

猜你喜欢

转载自blog.csdn.net/coder_my_lover/article/details/105237995