zoukankan      html  css  js  c++  java
  • 将数组按照偶奇偶奇的顺序排序

    /**
     *  一个数组,一半奇数,一半是偶数,要将数组按照偶奇偶奇的顺序排序
     *  思路,找出下标是偶数但值是奇数的,和下标是奇数但值是偶数的,两个互换,直到结束
     */
    public class SortArrayByParityll {
    
        
        public static void main(String[] args) {
            
            int [] arr = new int[] {12,14,16,18,16,10,20,19,11,25,27,29,23,17};
            sort(arr);
            Arrays.stream(arr).forEach(s -> System.out.print(s+ " "));
            
        }
        
        private static void sort(int[] arr) {
            int i = 0 ;
            int j = 1;
            for(;i<arr.length && j<arr.length; ) {
                if(arr[i] % 2 == 0) {
                    i+=2;
                }else if(arr[j] % 2 == 1) {
                    j+=2;
                }else {
                    swap(i, j, arr);
                }
            }
        }
    
        
    
        public static  void swap(int a , int b , int [] arr) {
            int temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp; 
        }
        
    }
  • 相关阅读:
    分数加减法
    两点距离
    1的个数
    Swift 了解(1)
    ARC快速入门
    ARC基本概念
    autorelease注意事项
    autorelease基本使用
    NSTimer的使用
    如何监听控件的行为
  • 原文地址:https://www.cnblogs.com/moris5013/p/11805729.html
Copyright © 2011-2022 走看看