# 奇偶排序

4
2 3 1 23

3 1 23 2

...全文
1255 8 打赏 收藏 举报

8 条回复

• 打赏
• 举报

#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)) {
} else {
}
}
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)
{
}
else
{
}
}
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)

• 打赏
• 举报

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]);

9232

Study well and make progress every day

2023-03-03 14:00

2023-02-14 18:20

2023-02-08 10:20

2022-10-27 17:58

2022-08-31 17:42

2022-08-02 17:57