3446. 整数奇偶排序

3446.整数奇偶排序

⭐️难度:简单

⭐️类型:排序

📖题目:题目链接

🌟思路:考察sort函数自定义排序规则

因为自定义函数的两个参数 lhs 和 rhs 不发生交换时,才返回真

所以要找出 不交换的 情况:

📚题解:

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<vector>  // vector不需要.h
#include<list>
#include<set>  // // 可以用 set 和 multiset
#include<unordered_set> // 可以用 unordered_set 和 unordered_multimap
#include<map>  // 可以用 map 和 multimap
#include<unordered_map> // 可以用 unordered_map 和 unordered_multimap
#include<algorithm>

using namespace std;

bool compare(int lhs, int rhs) {
    if (lhs % 2 == 1 && rhs % 2 == 0) { // 左奇右偶,不交换
        return true;
    }
    else if (lhs % 2 == 1 && rhs % 2 == 1 && lhs > rhs) { // 左奇右奇 且 左>右,不交换
        return true;
    }
    else if (lhs % 2 == 0 && rhs % 2 == 0 && lhs < rhs) { // 左偶右偶 且 左<右,不交换
        return true;
    }
    else { // 其余情况全部交换
        return false; 
    }
}

int main() {
    int arr[10];
    for (int i = 0;i < 10;i++) {
        scanf("%d", &arr[i]);  // arr + i
    }
    sort(arr, arr + 10, compare);
    for (int i = 0;i < 10;i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}
相关推荐
hairenwangmiao5 小时前
B4041 [GESP202409 四级] 区间排序
算法·排序
csdn_aspnet7 天前
C# list集合 多属性排序
c#·list·linq·排序
8Qi810 天前
LeetCode 75:颜色分类(荷兰国旗问题)—— Java 题解 ✅
java·算法·leetcode·指针·排序
Misnearch10 天前
3635. 最早完成陆地和水上游乐设施的时间II
leetcode·贪心·排序
Dlrb121119 天前
数据结构-单链表与双链表
c语言·数据结构·链表·排序·双链表
郝学胜-神的一滴22 天前
干货版《算法导论》05:从集合接口到排序
开发语言·数据结构·c++·程序人生·算法·排序
汉克老师1 个月前
GESP5级C++考试语法知识(十四、分治算法(一))
算法·归并排序·排序·分治算法·gesp5级·gesp五级
汉克老师1 个月前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
Irene19912 个月前
数据排序为什么默认升序
算法·排序
浅念-2 个月前
分治算法专题|LeetCode高频经典题目详细题解
数据结构·c++·算法·leetcode·职场和发展·排序·分治