c++ - 如何在 C++ 中对数组进行自定义排序,但保留其中一部分未排序?

标签 c++ algorithm sorting

我想对一个数组进行排序,但保留了一部分。被遗漏的部分应由起始索引(n)和结束索引(m)指定。这两个索引之间的所有字段,包括两个指定的字段,都不应排序。所有其他的,包括间隔之前的和间隔之后的,都应该一起排序。

例如:

  • 输入序列号{10, 4, 11, 7, 6, 20}
  • 非排序区间起始索引n = 1
  • 非排序区间结束索引 m = 3 ,
  • 输出:{ 6 , 4 , 11 , 7 , 10 , 20 }

索引 1 到 3 的值为 4, 11, 7 的字段未排序。

#include <iostream>
#include <algorithm>
using namespace std;

int main () {
    int arr[5] = {10, 4, 11, 7, 6, 20};
    sort (arr,arr+5);
    for (int i = 0; i < 5; i++){
        cout << arr[i] << " ";
    }
    return 0;
}

我该怎么做?

最佳答案

这是一种使用 std::rotatestd::sort 的方法。
它将不应该排序的元素旋转到末尾,然后对开始部分进行排序,然后旋转回我们移动的元素。

#include <iostream>
#include <iterator>
#include <array>
#include <algorithm>

int main() {
    std::array<int, 6> arr = {10, 4, 11, 7, 6, 20};

    unsigned from = 1;
    unsigned to = 3;

    unsigned distance = to - from + 1;

    if (to + 1 != arr.size())
        std::rotate(arr.begin(), arr.begin() + to + 1, arr.end());

    std::sort(arr.begin(), arr.end() - distance);

    std::rotate(arr.begin() + from, arr.end() - distance, arr.end());

    for (auto v : arr)
        std::cout << v << ' ';
}

我使用了 std::array 而不是 c 风格的数组。也适用于 std::vector

关于c++ - 如何在 C++ 中对数组进行自定义排序,但保留其中一部分未排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480377/

相关文章:

c++ - Webots中的无人机模拟

c# 将字母转换为数字以进行二分查找

使用 Nulls_Last 处理进行 Spring 排序不起作用

c++ - C++ 中与 Matlab 中的 wpd 和 newpnn 函数类似的函数?

c++ - 使用 C++11 正则表达式匹配文本范围

从视频源确定房间大小的算法

c++ - 基于最大公除法的排序顺序

php - 使用优先级对 MySQL 搜索结果进行排序

c - 我对这个函数做错了什么,它没有结束

c++ - 在 C++ 中的类中调用函数?