9232
社区成员
#include
using namespace std;
int Exchange(int *a,int *b);
int main()
{
int num[20],n,i,k=0;
cout<<"请输入正整数n:";
cin>>n;
cout<<"请输入n个整数:";
for(i=0;i<n;i++)
{
cin>>num[i];
}
for(i=0;i<n;i++)
{
if(num[i]%2)
{
k+=Exchange(&num[k],&num[i]);
}
}
for(i=0;i<n;i++)
{
cout<<num[i]<<" ";
}
cout<<endl;
return 0;
}
int Exchange(int *a,int *b)
{
int temp,count=0;
temp=*a;
*a=*b;
*b=temp;
count+=1;
return count;
}
public class TestDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整数");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("请输入长度为" + n + "的数组,格式如:23 4 6 21 5 82");
for (int i = 0; i < arr.length; i++) {
// 把数据按照从0开始的下标存入arr 数组
arr[i] = scanner.nextInt();
// 输出存入的数组
System.out.print(arr[i] + " ");
}
System.out.println();
List<Integer> oddList = new ArrayList<>();
List<Integer> evenList = new ArrayList<>();
for (int i : arr) {
if (isOddNumber(i)) {
oddList.add(i);
} else {
evenList.add(i);
}
}
oddList.addAll(evenList);
System.out.println("调整数组顺序使奇数位于偶数前面:");
for (Integer num : oddList) {
System.out.print(num + " ");
}
System.out.println();
}
public static boolean isOddNumber(int num) {
return num % 2 != 0;
}
}
function odd(array) {
return array.sort((preItem, nextItem) => {
let number;
try {
number = preItem % 2 == 1 && nextItem % 2 == 0 ? -1 : 1;
} catch (error) {
number = -1;
}
return number;
});
}
const array = [2, 3, 1, 23];
console.log(odd(array));
n = int(input())
a = list(map(int, input().split()))
left, right = 0, n - 1
while left < right:
# 左指针向右移动,直到找到第一个偶数
while left < right and a[left] % 2 != 0:
left += 1
# 右指针向左移动,直到找到第一个奇数
while left < right and a[right] % 2 == 0:
right -= 1
# 交换左右指针所指向的元素
a[left], a[right] = a[right], a[left]
print(' '.join(map(str, a)))
List testList = new List() { 2, 3, 1, 23 };
testList.Sort((x, y) =>
{
return (y%2).CompareTo((x%2));
});
string result = "";
for (int i = 0; i < testList.Count; i++)
{
result = string.Format("{0} {1}", result, testList[i]);
}
Console.WriteLine(result);
int[] a1 = { 3, 5, 4, 9, 22, 55 };
List jishu = new List();
List houshu = new List();
for (int i=0;i<a1.Length;i++)
{
if (a1[i]%2==0)
{
houshu.Add(a1[i]);
}
else
{
jishu.Add(a1[i]);
}
}
string aaa = "";
if (jishu.Count>0)
{
for (int i=0;i<jishu.Count;i++)
{
aaa += jishu[i] + " ";
}
for (int j=0;j<houshu.Count;j++) {
aaa += houshu[j] + " ";
}
}
n = int(input())
nums = list(map(int, input().split()))
nums.sort(key=lambda x: x % 2)
print(nums)
这段代码首先读取了输入的 n,然后使用 input().split() 将输入的 n 个整数分割为列表。接着使用 sort() 方法将列表排序,使用 lambda x: x % 2 作为关键字,这样奇数就会排在偶数前面。最后,输出排序后的数组。
var odd=[];
var even=[];
var n=4;
var m=[2,3,1,23];
for(var i=0;i<n;i++){
if(m[i]%2==1){
odd.push(m[i]);
}else{
even.push(m[i]);
}
}
console.log([...odd,...even]);