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;
}
相关推荐
Irene19918 小时前
数据排序为什么默认升序
算法·排序
浅念-1 天前
分治算法专题|LeetCode高频经典题目详细题解
数据结构·c++·算法·leetcode·职场和发展·排序·分治
漂流瓶jz10 天前
UVA-120 煎饼 题解答案代码 算法竞赛入门经典第二版
数据结构·c++·算法·排序·aoapc·算法竞赛入门经典·uva
闻缺陷则喜何志丹10 天前
【排序 离散化 二维前缀和】 P7149 [USACO20DEC] Rectangular Pasture S|普及+
c++·算法·排序·离散化·二维前缀和
闻缺陷则喜何志丹12 天前
【排序】P6149 [USACO20FEB] Triangles S|普及+
c++·算法·排序·洛谷
Tairitsu_H15 天前
C语言:排序(一)
c语言·数据结构·排序
起个破名想半天了22 天前
算法与数据结构之排序
数据结构·排序算法·排序·算法与数据结构
问好眼1 个月前
《算法竞赛进阶指南》0x05 排序-1.电影
c++·算法·排序·信息学奥赛
汉克老师1 个月前
GESP2026年3月认证C++五级( 第三部分编程题(2)找数)
c++·排序·双指针·二分算法·gesp5级·gesp五级
伟大的车尔尼1 个月前
双指针题目:满足条件的子序列数目
二分查找·排序·双指针