将数组的奇数放在左边,偶数放在右边

/**
 *  使用两个指针i和j,初始化均为0。然后j往后遍历,若遇到了奇数,则将 A[j] 和 A[i] 交换位置,同时i自增1,这样操作下来,同样可以将所有的偶数都放在奇数前面
 *
 */
public class SortArrayByParity {

    
    public static void main(String[] args) {
        
        int [] arr = new int[] {2,3,4,5,6,7,8,9,10,12,14,15,16,17};
        sort(arr);
        Arrays.stream(arr).forEach(s -> System.out.print(s+ " "));
    }
    
    
    public static void sort(int [] arr) {
        int i = 0 ;
        for(int j = 0 ; j < arr.length ; j ++) {
            if(arr[j] % 2 == 1 ) {
                swap(j,i,arr);
                i++;
            }
        }
    }
    
    public static  void swap(int a , int b , int [] arr) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp; 
    }
}

猜你喜欢

转载自www.cnblogs.com/moris5013/p/11805110.html
今日推荐