将数组的奇数放在左边,偶数放在右边
Posted moris5013
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将数组的奇数放在左边,偶数放在右边相关的知识,希望对你有一定的参考价值。
/** * 使用两个指针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; } }
以上是关于将数组的奇数放在左边,偶数放在右边的主要内容,如果未能解决你的问题,请参考以下文章
java中怎么将1个数组的数其中偶数放在b1数组里,奇数放在b2数组里?