输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于偶数前面

本文介绍了一种通过调整数组中数字顺序的方法,确保所有奇数位于偶数之前。提供了两种实现方式,一种使用双指针技术进行高效排序,另一种采用简单的交换算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.sort;

//输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于偶数前面

public class Test1 {
	public static void main(String args[]) {
		int a[] = { 1, 2, 3, 4, 5, 6, 7, 9, 10, 12, 14, 11 };
		int n = 12;
		System.out.println("before transformation\n");
		for (int i = 0; i < n; i++)
			System.out.print(a[i]+" ");
		System.out.println();
		transformation(a, n);
		return;
	}

	public static boolean isEven(int a) {
		return a % 2 == 0 ? true : false;
	}

	public static void transformation(int data[], int n) {
		int begin = 0;
		int end = n - 1;
		while (begin < end) {
			if (!isEven(data[begin])) {
				begin++;
				continue;
			}
			if (isEven(data[end])) {
				end--;
				continue;
			}
			int c = data[begin];
			data[begin] = data[end];
			data[end] = c;
		}
		System.out.println("after transformation\n");
		for (int i = 0; i < n; i++)
			System.out.print(data[i]+" ");
		System.out.println();
	}
}
package com.sort;

//输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于偶数前面
public class Test {
	public static void main(String args[]) {
		int[] a = { 2, 3, 4, 2, 3, 1, 6, 1 };
		int c = 0;
		for (int i = 0; i < a.length; i++) {
			if (a[i] % 2 > 0) {
				continue;
			} else {
				for (int j = i + 1; j < a.length; j++) {
					if (a[j] % 2 > 0) {
						c = a[i];
						a[i] = a[j];
						a[j] = c;
					} else {
						continue;
					}
				}
			}
		}
		for(int j = 0 ; j < a.length;j++){
			System.out.print(a[j]+" ");
		}

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值